我在将列集更新为主键时遇到问题,即使我在更新集默认
上进行了更新这是我创建表的代码,我设置了更新集默认
create table department(
id int default 10 primary key,
name varchar(50)
);
create table employee
(
id int primary key,
dept_id int default 40 foreign key references department(id) on update set default on delete set default,
name varchar(40)
);
之后,我将数据插入表
insert into department
values
(1,'hr'),
(2,'programming'),
(3,'telesales'),
(4,'database')
insert into employee
values
(1,1,'mohammed'),
(2,2,'magd'),
(3,1,'soha'),
(4,3,'sameh'),
(5,4,'ashraf')
但是,当我运行此代码来更新列id
时update department
set id = 44 where id = 4
我收到了这个错误
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK__employee__dept_i__571DF1D5". The conflict occurred in database "test", table "dbo.department", column 'id'.
The statement has been terminated.
但我不知道我的错在哪里!
感谢
答案 0 :(得分:2)
在外键约束中使用ON UPDATE CASCADE
,如下所示:
create table employee
(
id int primary key,
dept_id int default 40 foreign key references department(id) on update cascade on delete set default,
name varchar(40)
);
如果id
列值有任何更新,dept_id
也会更新以跟随更改后的值。
答案 1 :(得分:1)
由于employee
表格dept_id
列 *约束* ,id
列department
。更新表的主键时会遇到此错误,但是来自另一个表的外键引用该错误,并且特定于更新的设置为“无操作”。 No操作是默认选项。
如果是这种情况并且未对更新操作设置操作,则可以将外键定义更改为Cascade
你可以试试这个:
ALTER TABLE employee
DROP Constraint FK__employee__dept_i__571DF1D5
GO
ALTER TABLE employee
ADD CONSTRAINT New_FK_Constraint
FOREIGN KEY (dept_id) REFERENCES department (id)
ON DELETE CASCADE ON UPDATE CASCADE
GO
答案 2 :(得分:1)
通常会出现该错误,您有一个外键关系,然后您更改该值。
在外键约束中使用ON UPDATE CASCADE
答案 3 :(得分:0)
如果不想更改表结构,可以运行以下查询:
ALTER TABLE [UserStore]
NOCHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE [UserIdentity]
NOCHECK CONSTRAINT FK_UserIdentity_User_UserId
BEGIN TRAN
UPDATE [user]
SET Id = 10
WHERE Id = 9
UPDATE [dbo].[UserStore]
SET UserId = 10
WHERE UserId = 9
UPDATE [dbo].UserIdentity
SET UserId = 10
WHERE UserId = 9
COMMIT TRAN
ALTER TABLE [UserStore]
CHECK CONSTRAINT FK_UserStore_User_UserId
ALTER TABLE UserIdentity
CHECK CONSTRAINT FK_UserIdentity_User_UserId