以下是我必须回答的问题:
以下是我的代码:
CREATE TRIGGER Products_INSERT
ON Products
AFTER INSERT
AS
UPDATE Products
SET DateAdded = GETDATE()
WHERE DateAdded IS NULL OR
DateAdded IN (SELECT DateAdded FROM inserted);
这是我的插入声明:
INSERT INTO Products
VALUES (4, 'LK-5300', 'Likeable Keyboard 5300',
'This keyboard is so cool, you just might flip!',
699.99, 30.00, NULL)
以下是我不断得到的错误:
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Products__Catego__145C0A3F". The conflict occurred in database "MyGuitarShop", table "dbo.Categories", column 'CategoryID'.
The statement has been terminated.
我知道错误与外键有关,但我并不完全确定。任何帮助将不胜感激。
编辑:
CREATE TABLE Products (
ProductID INT PRIMARY KEY IDENTITY,
CategoryID INT REFERENCES Categories (CategoryID),
ProductCode VARCHAR(10) NOT NULL UNIQUE,
ProductName VARCHAR(255) NOT NULL,
Description TEXT NOT NULL,
ListPrice MONEY NOT NULL,
DiscountPercent MONEY NOT NULL DEFAULT 0.00,
DateAdded DATETIME DEFAULT NULL
);
这是Products表
答案 0 :(得分:0)
感谢@Turophile这是我在阅读你的帖子后最终对我的INSERT语句所做的事情:
INSERT INTO Products (CategoryID, ProductCode, ProductName, Description, ListPrice,DiscountPercent, DateAdded)
VALUES (44444, 'LK-5300', 'Likeable Keyboard 5300',
'This keyboard is so cool, you just might flip!',
699.99, 30.00, NULL)
答案 1 :(得分:-1)
您的INSERT
应该是:
INSERT INTO Products
( CategoryID,
ProductCode,
ProductName,
Description,
ListPrice,
DiscountPercent,
DateAdded
)
VALUES (4, 'LK-5300', 'Likeable Keyboard 5300',
'This keyboard is so cool, you just might flip!',
699.99, 30.00, NULL)
您的INSERT缺少一个值进入ProductID
列,因为它是自动生成的,因为它被定义为IDENTITY但要使其起作用,您需要命名列,省略{{ 1}}。