自引用FK-更新语句与外键约束冲突
我有一个测试表员工,它具有自我引用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论