我有一张表格如下:
create table temp_cte1(id int primary key,name nvarchar(max))
另一张表格如下:
create table temo_cte2(id int,name nvarchar(max)),constraint fk_id foreign key(id) references temp_cte1(id)
我们假设两个表中都有以下值:
insert into temp_cte1 values(1,'Vinay'),(2,'Afzal'),(3,'Yogesh'),(4,'Shashank')
insert into temp_cte2 values(1,'Arya'),(2,'Hussain'),(3,'Kwatra'),(4,'Sharma')
现在,只要我使用cte更新任何表的'name'列,它就可以正常工作。 但是当我尝试更新id时,由于外键被侵犯,我收到错误。
查询工作正常:
with cte(id,FirstName,LastName) as(select t1.id,t1.name FirstName,t2.name LastName from temp_cte1 t1 inner join temp_cte2 t2 on t1.id=t2.id)
update cte set LastName='Arya' where id=1
但我需要做的是这样的事情:
with cte(id,FirstName,LastName) as(select t1.id,t1.name FirstName,t2.name LastName from temp_cte1 t1 inner join temp_cte2 t2 on t1.id=t2.id)
update cte set id=1222 where FirstName='Vinay'
对此有任何帮助???提前谢谢。
答案 0 :(得分:1)
我认为这应该适合你:
ALTER TABLE temp_cte2 NOCHECK CONSTRAINT ALL
;with cte(id,FirstName,LastName) as(select t1.id,t1.name FirstName,t2.name LastName from temp_cte1 t1 inner join temp_cte2 t2 on t1.id=t2.id)
update cte set id=12232 where FirstName='Yogesh'
ALTER TABLE temp_cte2 CHECK CONSTRAINT ALL
How can foreign key constraints be temporarily disabled using T-SQL?