SQL:INSERT语句与FOREIGN KEY约束冲突

时间:2016-02-05 12:17:52

标签: sql sql-server database foreign-keys sql-insert

我是SQL新手,目前正在使用MS SQL Server Management Studio。我已经获得了一项任务,我必须在其中创建包含某些表的数据库。其中两个表名为“产品”和“类别”。在创建了所有表之后,我必须填充它们(在其中插入记录)并且它就在这里我被卡住了。

这是创建两个表的代码:

分类表:

CREATE TABLE Categories (
    CategoryID NCHAR(3) PRIMARY KEY,
    Name NVARCHAR(50) NOT NULL);

产品表:

CREATE TABLE Products (
    ProductID INT identity(1,1) PRIMARY KEY,
    Name NVARCHAR(50) NOT NULL,
    [Single Price] MONEY NOT NULL,
    CategoryID NCHAR(3) NOT NULL,
    FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID));

这里我将数据插入到Categories表中:

INSERT INTO Categories (CategoryID, Name)
VALUES ('BKS', 'Books'),
       ('MSC','Music'),
       ('HDW', 'Hardware'),
       ('SFW', 'Software');

到目前为止一切顺利。这就是问题出现的地方! 我正在尝试将数据插入到Products表中,如下所示:

INSERT INTO Products (Name, [Single Price], CategoryID)
VALUES ('SQL for Dummies', 39.99, 'BKS'),
       ('The Power of Now', 24.99, 'BKS'),
       ('Steve Jobs: The Book', 29.99, 'BKS'),
       ('Eminem albums', 19.99, 'MSC'),
       ('Jay Z albums', 23.99, 'MSC'),
       ('Notorious B.I.G. albums', 24.99, 'MSC'),
       ('GeForce GT 710 2GB graphics card', 49.99, 'HDW'),
       ('2 TB T3 SSD', 79.99, 'HDW'),
       ('Acer Curved Gaming monitor', 259.99, 'HDW'),
       ('MS SQL Server Management Studio', 59.99, 'STW'),
       ('Visual Studio 2015', 69.99, 'SFW'),
       ('GTA V', 79.99, 'SFW');

我收到以下错误:

INSERT语句与FOREIGN KEY约束冲突”FK__Products__Catego__99BF96C4“。冲突发生在数据库”HackCompany“,表”dbo.Categories“,列'CategoryID'。

声明已经终止。“

如果有人提供任何帮助,我们将不胜感激!

2 个答案:

答案 0 :(得分:1)

问题是数据中没有一个或多个类别。您可以使用select语句找到它:

SELECT v.*
FROM (VALUES ('SQL for Dummies', 39.99, 'BKS'),
             ('The Power of Now', 24.99, 'BKS'),
             ('Steve Jobs: The Book', 29.99, 'BKS'),
             ('Eminem albums', 19.99, 'MSC'),
             ('Jay Z albums', 23.99, 'MSC'),
             ('Notorious B.I.G. albums', 24.99, 'MSC'),
             ('GeForce GT 710 2GB graphics card', 49.99, 'HDW'),
             ('2 TB T3 SSD', 79.99, 'HDW'),
             ('Acer Curved Gaming monitor', 259.99, 'HDW'),
             ('MS SQL Server Management Studio', 59.99, 'STW'),
             ('Visual Studio 2015', 69.99, 'SFW'),
             ('GTA V', 79.99, 'SFW')
      ) as v(Name, [Single Price], CategoryID)
WHERE NOT EXISTS (select 1 from categories c where v.categoryID = c.categoryID)

答案 1 :(得分:0)

类别' STW'表中不存在

相关问题