2017-06-14 54 views
-1
CREATE table dbo.PRODUCTS(

[Product ID] int not null, 
[Product name] varchar(20) not null, 
[Min price] decimal(10,2) not null, 
[Artist ID] varchar(20)not null, 
[genre] varchar(20)not null, 


primary key ([Product ID]), 

constraint ARTIST FOREIGN KEY ([Artist ID]) 
REFERENCES ARTISTS ([Artist email]), 
) 


CREATE table dbo.ORDERS_DETAILS(

[Purchase number] int not null, 
[Product ID] int not null, 
[Total price] decimal(10,2) not null, 
primary key ([Purchase number],[Product ID]), 

constraint DF_PRODUCT FOREIGN KEY ([Product ID]) 
****REFERENCES PRODUCTS ([Product ID]),**** 
constraint fk_PURCHASE FOREIGN KEY ([Purchase number]) 
REFERENCES PURCHASES ([Purchase number]), 
) 

錯誤:我不明白爲什麼外鍵約束沒有產品ID工作

Foreign key 'DF_PRODUCT' references invalid column 'Product ID' in referenced table 'PRODUCTS'.

有人可以幫助我瞭解爲什麼這個返回此錯誤?它無法識別產品表中的產品ID列,即使該表已正確創建並且正在工作。

+1

嘗試在右括號之前刪除結尾逗號。我創建了兩個表都很好。 –

+0

請顯示您確實運行的確切代碼。請儘可能多地打開錯誤報告。請閱讀[mcve]並採取行動。 – philipxy

+1

@WEI_DBA尾隨逗號不相關,這在T-SQL中是可以接受的,並且通常在生成的代碼中找到。 @Maya我也創建了兩個表,我猜你可能有另一個名爲'PRODUCTS'的表,除了'dbo.PRODUCTS'之外,有一個不同的模式。試試'REFERENCES dbo.PRODUCTS([Product ID]),'代替。 – pcdev

回答

0

在再次創建表之前刪除表。

IF EXISTS (SELECT * FROM sys.all_objects 
WHERE type_desc = 'USER_TABLE' 
AND name = 'PRODUCTS') 
BEGIN 
    DROP TABLE [PRODUCTS] 
END 

IF EXISTS (SELECT * FROM sys.all_objects 
WHERE type_desc = 'USER_TABLE' 
AND name = 'ORDERS_DETAILS') 
BEGIN 
    DROP TABLE [ORDERS_DETAILS] 
END 

然後根據預期創建您的表格。

相關問題