SQL Server creates tables in wrong database - sql

I want to create a new database and fill it up with some tables. It creates a new database but the tables appear in another database.
The ##DbName contains the name of the database the user gave in, the fact that it is creating a database says the DbName is correct. When executed the database is created but empty, all tables are inserted in another database.
I believe the error lies in the USE [##DbName]
What am I doing wrong?
My SQL statements:
CREATE DATABASE [##DbName]
ON PRIMARY
( NAME = [##DbName],
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\##DbName.mdf',
SIZE = 5 MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 1 MB )
LOG ON
( NAME = [##DbName_log],
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\##DbName_log.ldf',
SIZE = 1 MB,
MAXSIZE = 2097152 MB,
FILEGROWTH = 10 % )
COLLATE Latin1_General_CI_AS
GO
CREATE LOGIN [##DbLogin] WITH PASSWORD=N'##DbPassword', DEFAULT_DATABASE=[##DbName], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
USE [##DbName]
GO
CREATE TABLE [dbo].[Customers]
(
[ID] int IDENTITY(1, 1) NOT NULL,
[CustomerName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Address] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Picture] image NOT NULL,
[Balance] decimal(18, 2) NOT NULL
)
ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Employee]
(
[ID] int IDENTITY(1, 1) NOT NULL,
[EmployeeName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Address] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Email] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Phone] varchar(20) COLLATE Latin1_General_CI_AS NOT NULL
)
ON [PRIMARY]
GO
CREATE TABLE [dbo].[Registers]
(
[ID] int IDENTITY(1, 1) NOT NULL,
[RegisterName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Device] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL
)
ON [PRIMARY]
GO
CREATE TABLE [dbo].[Errorlog]
(
[RegisterID] int NOT NULL,
[Timestamp] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Message] varchar(255) COLLATE Latin1_General_CI_AS NOT NULL,
[StackTrace] ntext COLLATE Latin1_General_CI_AS NOT NULL
)
ON [PRIMARY]
TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Products]
(
[ID] int IDENTITY(1, 1) NOT NULL,
[ProductName] varchar(50) COLLATE Latin1_General_CI_AS NOT NULL,
[Price] decimal(18, 2) NULL
)
ON [PRIMARY]
GO
CREATE TABLE [dbo].[Register_Employee]
(
[RegisterID] int NOT NULL,
[EmployeeID] int NOT NULL,
[From] varchar(20) COLLATE Latin1_General_CI_AS NOT NULL,
[Until] varchar(20) COLLATE Latin1_General_CI_AS NOT NULL
)
ON [PRIMARY]
GO
CREATE TABLE [dbo].[Sales]
(
[ID] int NOT NULL,
[Timestamp] timestamp NOT NULL,
[CustomerID] int NOT NULL,
[RegisterID] int NOT NULL,
[ProductID] int NOT NULL,
[Amount] int NOT NULL,
[TotalPrice] decimal(18, 2) NOT NULL
)
ON [PRIMARY]
GO

Related

Deadlock in SQL

I have multiple python scripts that run in parallel and insert/update 2 tables.
Table 1: Nmap_Scans_Hosts
Table 2: Nmap_Scans_Ports
Both these tables have no PK, only a FK referencing a 3rd table Nmap_Scans.
When the scripts run, I get a deadlock on the tables. The scripts use pymssql and cursors for inserting/updating data.
The statements the scripts run are the following:
update lan.nmap_scans set latest = 0 where latest = 1 and target = '{target}'
INSERT INTO nvlanteam.LAN.Nmap_Scans
UPDATE nvlanteam.LAN.Nmap_Scans_Hosts SET Latest = 0 WHERE Host_Address = '{host_address}' and Tags = '{args.tags}'
INSERT INTO nvlanteam.LAN.Nmap_Scans_Hosts
UPDATE nvlanteam.LAN.Nmap_Scans_Ports SET Latest = 0 WHERE Host_Address = '{host_address}' AND Port is NULL
INSERT INTO nvlanteam.LAN.Nmap_Scans_Ports
update nvlanteam.lan.Nmap_Scans_Ports set Latest = 0 where Host_Address = '{host_address}' and Port = '{port_number}'
INSERT INTO nvlanteam.LAN.Nmap_Scans_Ports
The first 2 statements are only run once per script, while the other 6 are run in a loop for each ip address.
I tried setting pymssql's autocommit = True option but deadlocks still occur. Snapshot isolation is also enabled at database level.
Is there anything inherently wrong with my design? Or is there an option that I could enable that would prevent these deadlocks from occuring? Also, I know SQL Server kills one of the 2 deadlocked processes, but in my case, deadlocks are not resolved by SQL Server until I kill one of the Python processes.
Edit:
Included the DDL for the tables used.
CREATE TABLE nvlanteam.LAN.Nmap_Scans (
Target varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Hosts_Total int NULL,
Hosts_Up int NULL,
Scan_ID int IDENTITY(0,1) NOT NULL,
Scan_Server varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Scan_Command varchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Scan_Start datetime NULL,
Scan_Finish datetime NULL,
Elapsed int NULL,
Latest bit NULL,
Tags varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT Nmap_Scans_PK PRIMARY KEY (Scan_ID)
);
CREATE TABLE nvlanteam.LAN.Nmap_Scans_Hosts (
Scan_ID int NOT NULL,
Host_Address varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Host_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Region varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Country varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Location varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Division varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Subnet_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CIDR varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Reason varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
RTT float NULL,
Latest bit NULL,
Tags varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
);
-- nvlanteam.LAN.Nmap_Scans_Hosts foreign keys
ALTER TABLE nvlanteam.LAN.Nmap_Scans_Hosts ADD CONSTRAINT Nmap_Scans_Hosts_FK FOREIGN KEY (Scan_ID) REFERENCES nvlanteam.LAN.Nmap_Scans(Scan_ID) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE nvlanteam.LAN.Nmap_Scans_Ports (
Scan_ID int NULL,
Host_Address varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Port int NULL,
Protocol varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
State varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Reason varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Reason_TTL int NULL,
Service_Name varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Service_Product varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Service_Version varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Service_Extra_Info varchar(1000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Device_Type varchar(100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Latest bit NULL
);
-- nvlanteam.LAN.Nmap_Scans_Ports foreign keys
ALTER TABLE nvlanteam.LAN.Nmap_Scans_Ports ADD CONSTRAINT Nmap_Scans_Ports_FK FOREIGN KEY (Scan_ID) REFERENCES nvlanteam.LAN.Nmap_Scans(Scan_ID) ON DELETE CASCADE ON UPDATE CASCADE;

STContains returns points that are not in polygon

I am trying to get points from a Microsoft SQL Server table that are inside a polygon from another table. The current query results in points outside the definition of the polygon.
The main query I have is this:
select top 10
ATOMIZER.[ATOMIZER_ID]
,ATOMIZER.LAT
,ATOMIZER.LONG
from db..ATOMIZER join db..[AOI]
on ATOMIZER.ZIP = Cast(AOI.[zip] AS varchar)
where 1 = CASE AOI.TYPE
WHEN 'polygon' THEN AOI.[geography].STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326))
WHEN 'rectangle' THEN AOI.[geography].STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326))
WHEN 'circle' THEN AOI.[geography].STContains(AOI.[geography].STBuffer(AOI.radius)) END
and AOI.id = {AOI}
--and AOI.DateLicensed is null
and ATOMIZER.LAT is not null
and ATOMIZER.LONG is not null
I have also simplified the query to this in an attempt to troubleshoot.
select top 10
ATOMIZER.[ATOMIZER_ID]
,ATOMIZER.LAT
,ATOMIZER.LONG
from db..ATOMIZER join db..[AOI]
on ATOMIZER.ZIP = Cast(AOI.[zip] AS varchar)
where AOI.id = 9198
and ATTOM.LAT is not null
and ATTOM.LONG is not null
and AOI.geography.STContains(geography::Point(ATOMIZER.LAT, ATOMIZER.LONG, 4326)) = 1
The Atomizer Table looks like this:
CREATE TABLE db.dbo.ATOMIZER (
ATOMIZER_ID bigint NULL,
ADDRESS varchar(140) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CITY varchar(64) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
STATE varchar(8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
ZIP varchar(14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
LAT float NULL,
LONG float NULL,
GEOCODE_DT date NULL,
Geocodio_Address varchar(156) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Geocodio_City varchar(56) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Geocodio_State varchar(8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Geocodio_Zip varchar(14) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Geocodio_Lat float NULL,
Geocodio_Lng float NULL,
Geocodio_GEOID varchar(26) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
Geocodio_POINT geography NULL
);
The AOI table looks like this:
CREATE TABLE db.dbo.AOI (
ID int IDENTITY(1,1) NOT NULL,
name varchar(500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[type] varchar(50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[geography] geography
);
CREATE NONCLUSTERED INDEX NonClusteredIndex-20221206-185336 ON dbo.AOI ( zip ASC )
WITH ( PAD_INDEX = OFF ,FILLFACTOR = 100 ,SORT_IN_TEMPDB = OFF , IGNORE_DUP_KEY = OFF , STATISTICS_NORECOMPUTE = OFF , ONLINE = OFF , ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON )
ON [PRIMARY ] ;
In the main query, I'm looking at AOI 9198 The polygon in the polygon in the AOI appear like this:
[(27.334412613029517, -82.48118404236736),
(27.334488859974545, -82.4711418518156),
(27.329456449106882, -82.47105602112713),
(27.330218950286305, -82.48109821167888),
(27.334412613029517, -82.48118404236736)]
However, the results for that AOI returns ATOMIZER points outside the polygon:
[(243854600, 27.049499, -82.139568),
(243844656, 27.072806, -82.093464),
(250735272, 27.299072, -82.456513),
(145991001, 27.299082, -82.47212),
(145943693, 27.299085, -82.47242),
(25251051, 27.299086, -82.47049),
(16653415, 27.29909, -82.467433),
(10864549, 27.299091, -82.46352),
(163778547, 27.299092, -82.465079),
(49735501, 27.299093, -82.457673)]
These points lie outside the geography.
What am I missing here?
Thank you.

Query not using index in exists statement

I have the index IDX_tbl_SpeedRun_StatusTypeID_GameID_CategoryID_LevelID_PlusInclude on table dbo.tbl_SpeedRun below. The exists statement in the query below is taking a while (1m 10s) saying there is a missing index ON [dbo].[tbl_SpeedRun] ([StatusTypeID],[LevelID]).
Why is the exists statement not using the index I created? It already includes the columns [StatusTypeID],[LevelID].
Table:
CREATE TABLE [dbo].[tbl_SpeedRun]
(
[OrderValue] [int] NOT NULL IDENTITY(1,1),
[ID] [varchar] (50) NOT NULL,
[StatusTypeID] [int] NOT NULL,
[GameID] [varchar] (50) NOT NULL,
[CategoryID] [varchar] (50) NOT NULL,
[LevelID] [varchar] (50) NULL,
[SubCategoryVariableValues] [varchar] (1000) NULL,
[PlayerIDs] [varchar] (1000) NULL,
[PlatformID] [varchar] (50) NULL,
[RegionID] [varchar] (50) NULL,
[IsEmulated] [bit] NOT NULL,
[Rank] [int] NULL,
[PrimaryTime] [bigint] NULL,
[RealTime] [bigint] NULL,
[RealTimeWithoutLoads] [bigint] NULL,
[GameTime] [bigint] NULL,
[Comment] [varchar] (MAX) NULL,
[ExaminerUserID] [varchar] (50) NULL,
[RejectReason] [varchar] (MAX) NULL,
[SpeedRunComUrl] [varchar] (2000) NOT NULL,
[SplitsUrl] [varchar] (2000) NULL,
[RunDate] [datetime] NULL,
[DateSubmitted] [datetime] NULL,
[VerifyDate] [datetime] NULL,
[ImportedDate] [datetime] NOT NULL CONSTRAINT [DF_tbl_SpeedRun_ImportedDate] DEFAULT(GETDATE()),
[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_SpeedRun]
ADD CONSTRAINT [PK_tbl_SpeedRun]
PRIMARY KEY NONCLUSTERED ([ID]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX [IDX_tbl_SpeedRun_OrderValue]
ON [dbo].[tbl_SpeedRun] ([OrderValue]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_tbl_SpeedRun_StatusTypeID_GameID_CategoryID_LevelID_PlusInclude]
ON [dbo].[tbl_SpeedRun] ([StatusTypeID], [GameID], [CategoryID],[LevelID])
INCLUDE ([SubCategoryVariableValues], [PlayerIDs], [Rank],[PrimaryTime])
GO
Query:
SELECT
CASE
WHEN EXISTS (SELECT 1 FROM dbo.tbl_SpeedRun rn WITH (NOLOCK)
WHERE rn.LevelID = l.ID AND rn.StatusTypeID = 1)
THEN 1
ELSE 0
END
FROM
dbo.tbl_Level l WITH (NOLOCK)
WHERE
l.GameID = 'pd0wq901'
ORDER BY
l.OrderValue
This is the from clause of your subquery:
WHERE rn.LevelID = l.ID AND rn.StatusTypeID = 1
A helpful index for this predicate would involve the two columns, in any order.
Your existing index does not satisfy that requirement. It has columns:
[StatusTypeID], [GameID], [CategoryID], [LevelID])
INCLUDE ([SubCategoryVariableValues], [PlayerIDs], [Rank], [PrimaryTime])
Both columns are here, but buried within others - so the database cannot take advantage of it to speed up the subquery.
Bottom line: creating a large index that involves a lot of columns does not speed up queries by default. Instead, you can analyze each query individually and define the proper optimization.

How do I rewrite this to avoid a cursor

I have this function written in T-SQL on SQL Server 2005. I am not as against cursors as some are but I always see people saying 99% of all cursors can be re-written to avoid their use.
I have this function:
CREATE FUNCTION WhereUsed(#ItemID varchar(100))
RETURNS varchar(MAX)
AS
BEGIN
DECLARE #Items CURSOR
DECLARE #ParentItem varchar(100)
DECLARE #WhereUsed varchar(MAX)
SET #WhereUsed = ''
SET #Items = CURSOR FAST_FORWARD
FOR
SELECT PST_ParentItemID FROM PST WHERE PST_CompItemID = #ItemID
OPEN #Items
FETCH NEXT FROM #Items
INTO #ParentItem
WHILE ##FETCH_STATUS = 0
BEGIN
SET #WhereUsed = #WhereUsed + #ParentItem + ', '
FETCH NEXT FROM #Items
INTO #ParentItem
END
IF LEN(#WhereUsed) > 2
SET #WhereUsed = LEFT(#WhereUsed, LEN(#WhereUsed) - 2)
RETURN #WhereUsed
END
Which will get all the items where a part is used, PST is ParentStructureTable. Think BOM (Bill Of Materials)
It will be used like this:
SELECT Field1, Field2, dbo.WhereUsed(ItemID), Field3 FROM Item
And return something like this:
S6110-23350-41, 61070-10161-012, R6112-23027-41
How could this be done without using a cursor?
EDIT:
Sample data
SELECT PST_ParentItemID FROM PST WHERE PST_CompItemID = #ItemID
Can return
PST_ParentItemID
----------------
S6110-23350-41
61070-10161-012
R6112-23027-41
Its really a simple select statement, not sure how the DDL will help but here it is:
CREATE TABLE [dbo].[ProductStructure](
[PST_RecordID] [uniqueidentifier] NOT NULL,
[PST_PSH_RecordID] [uniqueidentifier] NOT NULL,
[PST_IMA_RecordID] [uniqueidentifier] NOT NULL,
[PST_EffStartDate] [datetime] NOT NULL,
[PST_EffStopDate] [datetime] NULL,
[PST_DisplayOrder] [int] NOT NULL CONSTRAINT [DF__ProdStruc__PST_DisplayOrder] DEFAULT ((0)),
[PST_Available] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_Available] DEFAULT ((1)),
[PST_AddDate] [datetime] NOT NULL CONSTRAINT [DF__ProdStruc__PST_AddDate__192BAC54] DEFAULT (getdate()),
[PST_QtyPerAssy] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_QtyPerA__1A1FD08D] DEFAULT ((1)),
[PST_ScrapQty] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_ScrapQt__1B13F4C6] DEFAULT ((0)),
[PST_PlanType] [nvarchar](11) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF__ProdStruc__PST_PlanTyp__1C0818FF] DEFAULT ('MRP'),
[PST_ScrapPercent] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_ScrapPe__1CFC3D38] DEFAULT ((0)),
[PST_LeadTimeOffsetDays] [smallint] NOT NULL CONSTRAINT [DF__ProdStruc__PST_LeadTim__1DF06171] DEFAULT ((0)),
[PST_RoutSeqID] [nvarchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_EngChangeOrderID] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_FindID] [nvarchar](5) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_Comments] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UseAbsQtyFlag] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_UseAbsQ__1EE485AA] DEFAULT ((0)),
[PST_IgnoreCostFlag] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_IgnoreC__1FD8A9E3] DEFAULT ((0)),
[PST_PlanningPercent] [float] NOT NULL CONSTRAINT [DF__ProdStruc__PST_Plannin__20CCCE1C] DEFAULT ((0)),
[PST_EMP_RecordID] [uniqueidentifier] NULL,
[PST_LastModifiedDate] [datetime] NULL,
[PST_PurchPOWO] [bit] NOT NULL CONSTRAINT [DF__ProdStruc__PST_PurchPO__21C0F255] DEFAULT ((0)),
[PST_AgileCreatedDate] [datetime] NULL,
[PST_ArchiveDate] [datetime] NULL,
[PST_UserDef1] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef2] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef3] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef4] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[PST_UserDef5] [nvarchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[timestamp] [timestamp] NULL,
[PST_SWImportFlag] [bit] NOT NULL CONSTRAINT [DF_ProductStructure_PST_SWImportFlag] DEFAULT ((0)),
[PST_CopiedFromRecordID] [uniqueidentifier] NULL,
[PST_OnPicklist] [bit] NOT NULL DEFAULT ((1)),
[PST_CID_DocumentID] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_ProductStructure] PRIMARY KEY NONCLUSTERED
(
[PST_RecordID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
It appears you are simply returning a concatenated string. Try this
DECLARE #WhereUsed varchar(MAX)
SET #WhereUsed = ''
SELECT #whereUsed=#whereUsed+PST_ParentItemID+', 'FROM PST
WHERE PST_CompItemID = #ItemID
IF LEN(#WhereUsed) > 2
SET #WhereUsed = LEFT(#WhereUsed, LEN(#WhereUsed) - 2)

Why am I getting a multi-part identifier error in SQL?

There are some tables that we want to do a search.
I couldn't understand why this error happens , please help.
I should be easy for experts,
SELECT * FROM passenger
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
the Error :
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "ppp.passenger-id" could not be bound.
Tables are :
CREATE TABLE [dbo].[passenger](
[passenger-id] [int] IDENTITY(1,1) NOT NULL,
[name] [char](50) COLLATE Arabic_CI_AS NOT NULL,
[sex] [char](10) COLLATE Arabic_CI_AS NULL,
[mobile] [char](20) COLLATE Arabic_CI_AS NULL,
[address] [varchar](50) COLLATE Arabic_CI_AS NULL,
[flylist-id] [int] NOT NULL,
[chair-number] [char](10) COLLATE Arabic_CI_AS NOT NULL,
[Age] [char](10) COLLATE Arabic_CI_AS NULL,
[ticket-number] [char](10) COLLATE Arabic_CI_AS NULL,
CONSTRAINT [PK_passenger] PRIMARY KEY CLUSTERED
(
[passenger-id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Second
CREATE TABLE [dbo].[flylist](
[flylist-id] [int] IDENTITY(1,1) NOT NULL,
[fly-number] [varchar](50) COLLATE Arabic_CI_AS NOT NULL,
[go-date] [char](15) COLLATE Arabic_CI_AS NOT NULL,
[return-date] [char](15) COLLATE Arabic_CI_AS NOT NULL,
[go-time] [char](5) COLLATE Arabic_CI_AS NOT NULL,
[return-time] [char](5) COLLATE Arabic_CI_AS NOT NULL,
[start-from] [varchar](50) COLLATE Arabic_CI_AS NOT NULL,
[destination] [varchar](50) COLLATE Arabic_CI_AS NULL,
[airline-company-id] [int] NOT NULL,
[airplane-id] [int] NOT NULL,
CONSTRAINT [PK_flylist] PRIMARY KEY CLUSTERED
(
[flylist-id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Third
CREATE TABLE [dbo].[passenger-flylist](
[passenger-id] [int] NOT NULL,
[flylist-id] [int] NOT NULL,
CONSTRAINT [PK_passenger-flylist] PRIMARY KEY CLUSTERED
(
[passenger-id] ASC,
[flylist-id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [AirlineSx]
GO
ALTER TABLE [dbo].[passenger-flylist] WITH CHECK ADD CONSTRAINT [FK_passenger-flylist_passenger-flylist] FOREIGN KEY([passenger-id], [flylist-id])
REFERENCES [dbo].[passenger-flylist] ([passenger-id], [flylist-id])
If I had problem in setting the relations , please tell me how to do ,
thanks
Edited Part
Thanks , I found that in parallel with you , but I got another error :
( In my real code I want to get Passenger-id , but it doesn't allow me )
SELECT [passenger-id] FROM passenger ppp -- <<<< This line
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
INNER JOIN flylist fff ON ppff.[flylist-id] = fff.[flylist-id]
WHERE ppp.[name] = #name AND
fff.[start-from] = #flightDate AND
ppp.[ticket-number] = #ticketNo
The Error is:
Msg 209, Level 16, State 1, Procedure SearchForPassenger, Line 19
Ambiguous column name 'passenger-id'.
It refers to the 1st line that we want to select [passenger-id]
The problem is a missing alias ppp
SELECT * FROM passenger ppp
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
As to the second problem...
As passenger-id exists in both passenger and passenger-flylist you need to specify the alias of the table.
SELECT ppp.[passenger-id] FROM passenger ppp
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
INNER JOIN flylist fff ON ppff.[flylist-id] = fff.[flylist-id]
WHERE ppp.[name] = #name AND
fff.[start-from] = #flightDate AND
ppp.[ticket-number] = #ticketNo