2012-08-31 68 views
19

Error: There are no Primary or Candidate Keys in the referenced table 'dbo.Customers' that match the referencing column list in the foreign key 'FK_Reservation_Customers_FrstNme FOREIGN KEY'有在引用表上沒有主或候選鍵

DROP TABLE dbo.Customers; 
DROP TABLE dbo.Staff; 
DROP TABLE dbo.Rooms; 
DROP TABLE dbo.Reservation; 
GO 
CREATE TABLE "Customers"(

    CustomerID int IDENTITY (1,1) NOT NULL, 
    FirstName nvarchar(20) NULL, 
    LastName nvarchar(20) NULL, 
    StreetNo int NULL, 
    City nvarchar(20) NULL, 
    PostCode nvarchar(20) NULL, 
    Email nvarchar(50) NULL, 

    CONSTRAINT PK_Customers PRIMARY KEY 
    (
     CustomerID 
    ) 
) 
CREATE TABLE "Staff"(

    StaffID nvarchar(20) NOT NULL, 
    Pass nvarchar(20) NOT NULL, 

    CONSTRAINT PK_Staff PRIMARY KEY 
    (
     StaffID 
    ) 
) 
CREATE TABLE "Rooms"(

    RoomNo int NOT NULL, 
    RoomType nvarchar(20) NULL, 
    PricePerNight money NULL, 
    MaximumOccupancy int NULL, 
    No0fBeds int NULL, 
    NoOfBathrooms int NULL, 
    Entertainment bit NULL, 
    RoomService bit NULL, 
    Gym bit NULL, 

    CONSTRAINT PK_Rooms PRIMARY KEY 
    (
     RoomNo 
    ) 
) 
CREATE TABLE "Reservation"(

    ReservationID int IDENTITY (1,1) NOT NULL, 
    CustomerID int NOT NULL, 
    FirstName nvarchar(20) NULL, 
    LastName nvarchar(20) NULL, 
    RoomType nvarchar(20) NULL, 
    RoomNo int NOT NULL, 
    CheckInDate date NULL, 
    CheckOutDate date NULL, 

    CONSTRAINT PK_Reservation PRIMARY KEY 
    (
     ReservationID 
    ), 
    CONSTRAINT FK_Reservation_Customers_CustID FOREIGN KEY 
    (
     CustomerID 
    ) 
     REFERENCES dbo.Customers 
     (
      CustomerID 
     ), 
    CONSTRAINT FK_Reservation_Customers_FrstNme FOREIGN KEY 
    (
     FirstName 
    ) 
     REFERENCES dbo.Customers 
     (
      FirstName 
     ) 
    ) 

可能有人請告訴我發生了什麼在這裏和我怎麼能解決這個問題。所有其他鍵我想做一個外鍵發生同樣的問題。除非我想引用主鍵。

+4

您試圖添加映射到可空,不唯一的字段的外鍵... 順便說一句,您嘗試添加引用同一個表的兩個外鍵。你想用第二把鑰匙達到什麼目的? –

回答

36

如果要創建外鍵,它必須引用主鍵或具有唯一約束的字段。

如果要顯示客戶名稱,請將外鍵引用爲CustomerID,然後使用聯接顯示結果。

+0

謝謝,我現在明白了。 - 這也意味着我wouldint需要在保留名字和姓氏,如果即時通訊要使用連接來顯示客戶表中的名字和姓氏是否正確? – user1638362

+1

沒錯。除非您擔心在預訂時瞭解客戶的姓名,不管他們可能對其名稱所做的任何後續更改 – podiluska

2

當在引用表中指定與主鍵或候選鍵在參考表上定義的順序不同的鍵列時,我遇到了此錯誤。

切換指定列的順序修復了它。

例:

ALTER TABLE [dbo].[MCL_item_vendor_override_mst] WITH CHECK ADD 
CONSTRAINT [FK_MCL_item_vendor_override_mst_item_mst] FOREIGN KEY([item],[site_ref]) 
    REFERENCES [dbo].[item_mst] ([item],[site_ref]) 

失敗而

ALTER TABLE [dbo].[MCL_item_vendor_override_mst] WITH CHECK ADD 
CONSTRAINT [FK_MCL_item_vendor_override_mst_item_mst] FOREIGN KEY([site_ref],[item]) 
    REFERENCES [dbo].[item_mst] ([site_ref],[item]) 

工作。

相關問題