自引用FK-更新语句与外键约束冲突

发布于 2025-02-09 07:10:54 字数 987 浏览 2 评论 0原文

我有一个测试表员工,它具有自我引用fk manager_id

 CREATE TABLE employee (
   employee_id int IDENTITY PRIMARY KEY, 
   employee_name varchar(30), 
   salary varchar(30), 
   manager_id int
);

 ALTER TABLE employee
    ADD CONSTRAINT sr_fk_emp_man 
    FOREIGN KEY (manager_id)
    REFERENCES employee(employee_id)
;

 INSERT INTO employee (employee_name, salary) VALUES 
   ('ISACC NEWTON', 732611),
   ('ROMEO', 329827);

 UPDATE employee SET manager_id = 21 WHERE employee_name = 'ROMEO';

当我设置为pk lightsee_id int Identitiy时,会发生错误:

The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint "sr_fk_emp_man".
The conflict occurred in database "master", table "dbo.employee", column 'employee_id'.

我需要有自动填充的PK数字列。

我试图解决添加序列而不是Identitiy的问题,从而添加了FK(在更新级联的删除级联上)的参考完整性,并设置为fk null值,但没有任何变化。我可以使用NoCheck 约束使用,但我读到这不是最安全的选择。我正在使用MS SQL Server。

I have a test table employee which have self referencing FK manager_id:

 CREATE TABLE employee (
   employee_id int IDENTITY PRIMARY KEY, 
   employee_name varchar(30), 
   salary varchar(30), 
   manager_id int
);

 ALTER TABLE employee
    ADD CONSTRAINT sr_fk_emp_man 
    FOREIGN KEY (manager_id)
    REFERENCES employee(employee_id)
;

 INSERT INTO employee (employee_name, salary) VALUES 
   ('ISACC NEWTON', 732611),
   ('ROMEO', 329827);

 UPDATE employee SET manager_id = 21 WHERE employee_name = 'ROMEO';

Error occurs when I set for PK employee_id int IDENTITIY:

The UPDATE statement conflicted with the FOREIGN KEY SAME TABLE constraint "sr_fk_emp_man".
The conflict occurred in database "master", table "dbo.employee", column 'employee_id'.

I need to have for PK numeric column that is automatically populated.

I tried to solve a problem with adding sequence instead of IDENTITIY, adding Referential integrity for FK (ON DELETE CASCADE ON UPDATE CASCADE) and set for FK NULL value but nothing changes. I could use WITH NOCHECK Constraint but I read that is not the safest option. I am using MS SQL Server.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文