请考虑以下表格:
CREATE TABLE Foo
(
FooId1 int NOT NULL,
FooId2 int NOT NULL,
PRIMARY KEY(FooId1, FooId2)
);
INSERT INTO Foo(FooId1, FooId2) VALUES (1, 10), (2, 20);
CREATE TABLE Bar
(
BarId int NOT NULL PRIMARY KEY,
FooId1 int NULL,
FooId2 int NULL
);
ALTER TABLE Bar ADD CONSTRAINT FK_FOO
FOREIGN KEY(FooId1, FooId2)
REFERENCES Foo(FooId1, FooId2);
INSERT INTO Bar(BarId) VALUES(42);
如果我再尝试
UPDATE Bar
SET FooId1 = 3,
FooId2 = 30
WHERE BarId = 42;
我正按预期收到外键冲突。但是如果我这样做
UPDATE Bar
SET FooId1 = NULL,
FooId2 = 30
WHERE BarId = 42;
它可以正常工作。我本来希望即使字段FooId1
和FooId2
可以为空,但始终会针对外键检查这两者的组合。数据库为何允许此UPDATE
?
答案 0 :(得分:0)
在FOREIGN的列中输入非NULL的值时 KEY约束,该值必须存在于引用列中; 否则,将返回外键冲突错误消息。使 确保复合外键约束的所有值都是 验证后,在所有参与的列上指定NOT NULL。 Create Foreign Key Relationships
根据对 MSDN 的解释,您应该定义 Bar 的 Food1 和 Food2 列列具有非空约束。
CREATE TABLE Bar
(
BarId int NOT NULL PRIMARY KEY,
FooId1 int NOT NULL,
FooId2 int NOT NULL
)
这样以下插入将不起作用;
INSERT INTO Bar(BarId) VALUES(42)
Msg 515, Level 16, State 2, Line 23
Cannot insert the value NULL into column 'FooId1', table 'AdventureWorks2017.dbo.Bar'; column does not allow nulls. INSERT fails.
The statement has been terminated.