SQL INSERT 语句与 FOREIGN KEY SAME TABLE 约束冲突

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24812230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:14:20  来源:igfitidea点击:

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint

sqlsql-serverforeign-keys

提问by SanjayDVG

I have created table Employee

我已经创建了表 Employee

Create table Employee
(   
    FName varchar(20) Not Null,
    LName varchar(20) Not Null,
    SSN int Not Null,
    BDate Datetime,
    Address varchar(50),
    Sex char(1),
    Salary money,
    Super_SSN int,
    Primary Key(SSN),
    Foreign Key(Super_SSN) references Employee(SSN)
)

When i try to insert first row to ,

当我尝试插入第一行时,

insert into Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
values('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344) 

I am getting the error like..

我收到这样的错误..

Error:

错误:

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Employee_Employee". The conflict occurred in database "Company", table "dbo.Employee", column 'SSN'.

INSERT 语句与 FOREIGN KEY SAME TABLE 约束“FK_Employee_Employee”冲突。冲突发生在数据库“公司”、表“dbo.Employee”、列“SSN”中。

回答by Jesuraja

You need to first INSERT record for SSN '33344'with Super_SSN value as NULL.

您需要首先插入SSN '33344' 的记录,Super_SSN 值为NULL

INSERT INTO  Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES (<FName>,<LName>,'33344',<BDate>,<Address>,<Sex>,<Salary>,NULL)

After that insert

在那之后插入

INSERT INTO Employee (FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES ('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)

If SSN '33344'have any Super_SSN, update the SSN value (this record should be available in table).

如果SSN '33344'有任何Super_SSN,更新 SSN 值(此记录应在表中可用)。

回答by Vulcronos

The error is likely thrown because there is a foreign key from Super_SSNto SSNcolumn. You cannot insert a value of 33344into Super_SSNunless that value already exists in SSN. Try inserting nullinto Super_SSNor inserting user 33344first.

可能会抛出错误,因为从Super_SSNtoSSN列存在外键。你不能插入值33344Super_SSN,除非该值已经存在SSN。尝试插入nullSuper_SSN或插入用户33344第一。