不包含与引用匹配的主键或候选键

时间:2017-04-14 17:29:39

标签: sql sql-server database

  

SQL71516 ::引用的表' [dbo]。[MSTransaction]'不包含与外键中的引用列列表匹配的主键或候选键。如果引用的列是计算列,则应该保留它。

这是我收到的错误。有解决方案吗以下是两个表的SQL代码:

CREATE TABLE [dbo].[MSOrderline] 
(
    [PurchaseID] NCHAR (200) NOT NULL,
    [ProductID]  NCHAR (200) NOT NULL,
    [Quantity]   INT         NULL,

    CONSTRAINT [DoubleMS_PK] 
        PRIMARY KEY CLUSTERED ([PurchaseID] ASC, [ProductID] ASC),
    FOREIGN KEY ([PurchaseID]) REFERENCES [dbo].[MSTransaction] ([PurchaseID]),
    FOREIGN KEY ([ProductID]) REFERENCES [dbo].[MSProducts] ([ProductID])
);

CREATE TABLE [dbo].[MSTransaction] 
(
    [TransactionID] NCHAR (200) NOT NULL,
    [EmployeeID]    NCHAR (200) NULL,
    [CustomerID]    NCHAR (200) NULL,
    [PurchaseID]    NCHAR (200) NOT NULL,
    [Amount]        INT         NULL,
    [TotalAmount]   INT         NULL,
    [TimeOfSale]    NCHAR (200) NULL,
    [DiscountID]    NCHAR (200) NULL,

    PRIMARY KEY CLUSTERED ([TransactionID] ASC),

    FOREIGN KEY ([DiscountID]) REFERENCES [dbo].[MSDiscount] ([DiscountID]),
    FOREIGN KEY ([EmployeeID]) REFERENCES [dbo].[MSEmployee] ([EmployeeID]),
    FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[MSCustomer] ([CustomerID])
);

我知道以前曾经问过这个问题,但它要么在我的情况下不起作用,要么我无法适应我的情况。

1 个答案:

答案 0 :(得分:0)

正如Gordon Linoff所说,这些NCHAR(200)是群集密钥的可怕选择。

您必须先创建要引用的表。要将PurchaseId用作关键字,必须为unique

sql server中的示例:

CREATE TABLE [dbo].[MSTransaction] (
    [TransactionID] NCHAR (200) NOT NULL,
    [EmployeeID]    NCHAR (200) NULL,
    [CustomerID]    NCHAR (200) NULL,
    [PurchaseID]    NCHAR (200) NOT NULL unique,
    [Amount]        INT         NULL,
    [TotalAmount]   INT         NULL,
    [TimeOfSale]    NCHAR (200) NULL,
    [DiscountID]    NCHAR (200) NULL,
    PRIMARY KEY CLUSTERED ([TransactionID] ASC)
    --,FOREIGN KEY ([DiscountID]) REFERENCES [dbo].[MSDiscount] ([DiscountID]),
    --FOREIGN KEY ([EmployeeID]) REFERENCES [dbo].[MSEmployee] ([EmployeeID]),
    --FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[MSCustomer] ([CustomerID])
);
CREATE TABLE [dbo].[MSOrderline] (
    [PurchaseID] NCHAR (200) NOT NULL,
    [ProductID]  NCHAR (200) NOT NULL,
    [Quantity]   INT         NULL,
    CONSTRAINT [DoubleMS_PK] PRIMARY KEY CLUSTERED ([PurchaseID] ASC, [ProductID] ASC),
    FOREIGN KEY ([PurchaseID]) REFERENCES [dbo].[MSTransaction] ([PurchaseId]),
    --FOREIGN KEY ([ProductID]) REFERENCES [dbo].[MSProducts] ([ProductID])
);

rextester演示:http://rextester.com/ZVZD33282

在群集密钥上做出更好选择的参考: