我得到的错误是" INSERT语句与FOREIGN KEY约束冲突" FK_vacation_users"。冲突发生在数据库" TestAtt",table" dbo.users",column' userID'。"
我试图通过以下方式插入用户:
INSERT into users (firstName, lastName, userName, password, team, fingerID, type, isActive) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
firstNameAddBox.Text, lastNameAddBox.Text, userNameAddBox.Text, passwordAddBox.Text,
teamAddUserCombo.Text, fingerIdAddBox.Text, userTypeAddCombo.SelectedValue, isActiveCheck.Checked);
我的用户表如下所示:
CREATE TABLE
users
(
userID INT NOT NULL IDENTITY,
userName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
password NVARCHAR(100) COLLATE Romanian_CI_AS NOT NULL,
firstName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
lastName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
team TINYINT NOT NULL,
type TINYINT NOT NULL,
fingerID SMALLINT NOT NULL,
isActive BIT DEFAULT 1 NOT NULL,
CONSTRAINT PK_users PRIMARY KEY (userID),
CONSTRAINT FK_users_userType FOREIGN KEY (type) REFERENCES userType (typeID),
CONSTRAINT users_idx UNIQUE (fingerID)
);
假期表如下所示:
CREATE TABLE
vacation
(
ID INT NOT NULL IDENTITY,
userID INT NOT NULL,
vacation TINYINT DEFAULT 0 NOT NULL,
extraDays TINYINT DEFAULT 0 NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
);
这就是触发器:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
DECLARE @newUserID int
SELECT @newUserID = (SELECT userID FROM Inserted)
INSERT INTO vacation (userID) VALUES (@newUserID)
end;
因此,如果我禁用触发器,插件可以正常工作,但触发器似乎也不会在度假表中插入userID。
答案 0 :(得分:3)
我认为您的外键不正确,引用users
的列是userID
,而不是ID
:
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (userID)
但您的触发器也已损坏,因为inserted
可以包含多个(或无)行。所以它应该是:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
INSERT INTO vacation (userID) SELECT userID from Inserted
end;
答案 1 :(得分:0)
问题在于:
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
这就是假期中的ID列必须在用户的userId中具有匹配值。我认为(ID)应该是(userID)。它应该工作正常。
答案 2 :(得分:0)
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
应该是
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (ID)