再会
这个 SQL 脚本让我度过了一个奇怪的早晨 - 我收到以下错误(因为这个脚本是一个用于用虚拟数据填充表格的脚本):
Msg 547, Level 16, State 0, Line 7
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ATTR". The conflict occurred in database "PhonebookDuplication", table "dbo.Attributes_Dummy", column 'Id'.
The statement has been terminated.
正如问题所暗示的那样,该表中的行仍然被插入(好像它没有强制执行外键约束)
我还测试了手动插入数据 - 它不会抛出这个错误。
这是我的表格的布局和我执行的脚本。我需要知道发生了什么,以及为什么它会引发错误:) 我敢打赌它是我忽略的一些明显的东西。
脚本:
use PhonebookDuplication;
DROP TABLE Numbers_Attributes_Bridge;
DROP TABLE Numbers_Dummy;
DROP TABLE Attributes_Dummy;
CREATE TABLE Numbers_Dummy
(
Id int IDENTITY(1,1) PRIMARY KEY,
Number VARCHAR(20),
AccountId INT,
FirstName VARCHAR(20),
LastName VARCHAR(20)
);
CREATE TABLE Attributes_Dummy
(Id int IDENTITY(1,1) PRIMARY KEY,
AccountId INT,
Attribute VARCHAR(100)
);
CREATE TABLE Numbers_Attributes_Bridge
(
NumberId int,
AttributeId int,
AccountId int,
Value Varchar(100)
CONSTRAINT PK_NA PRIMARY KEY
(
NumberId ASC,
AttributeId ASC
)
CONSTRAINT FK_Numbers FOREIGN KEY (NumberId) REFERENCES Numbers_Dummy(Id),
CONSTRAINT FK_ATTR FOREIGN KEY (AttributeId) REFERENCES Attributes_Dummy(Id),
);
DECLARE @COUNTER INT = 0;
SET NOCOUNT ON
WHILE (@COUNTER < 150)
BEGIN
INSERT INTO Numbers_Dummy VALUES ('082'+CONVERT(varchar(15),@Counter),2000046,'Eon','du Plessis')
SET @COUNTER += 1;
END
SELECT COUNT(*) FROM Numbers_Dummy
SET @COUNTER = 0;
WHILE (@COUNTER < 5)
BEGIN
INSERT INTO Attributes_Dummy VALUES (2000046,'Attribute'+CONVERT(varchar(15),@Counter))
SET @COUNTER += 1;
END
SELECT COUNT(*) FROM Attributes_Dummy
DECLARE @COUNTER2 INT = 0 ;
DECLARE @SUBCOUNTER INT = 0;
WHILE (@COUNTER2 <= 150)
BEGIN
WHILE (@SUBCOUNTER <= 5)
BEGIN
INSERT INTO Numbers_Attributes_Bridge VALUES (@COUNTER2,@SUBCOUNTER,2000046, 'ATTRIBUTE-' + CONVERT(VARCHAR(100),@SUBCOUNTER))
SET @SUBCOUNTER =@SUBCOUNTER + 1;
END
SET @SUBCOUNTER = 0;
SET @COUNTER2 = @COUNTER2 + 1;
END
逻辑说 numbers_dummy 表将有 150 行,ID = 1 到 150 属性将有 5 行,ID = 1 - 5 Numbers_Attributes_Bridge 应该有 750 行: NumberID = 1 到 150,复合主键值为 AttributeID = 1 到 5
我收到上述错误,但行仍然插入。
以下代码行在手动测试中未引发错误:
INSERT INTO Numbers_Attributes_Bridge VALUES (150,5,2000046, 'ATTRIBUTE-5')
到底是怎么回事?