Sql 在两个表中使用cte进行更新

Sql 在两个表中使用cte进行更新,sql,sql-server,common-table-expression,Sql,Sql Server,Common Table Expression,我的表格如下: 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) 另一个表格如下: create table temp_cte1(id int primary key,name nvarchar(max))

我的表格如下:

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)
另一个表格如下:

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'

有什么帮助吗???提前谢谢。

我想这对你应该有用:

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

请问您为什么需要更新主键?这听起来不是个好主意,尤其是外键引用了它。不管这个主意听起来怎么样,问题是我办公室的高年级学生想要这个。处理这种情况,但是我不能强调更改主键是一个非常糟糕的主意。好的,那么当我试图更改外键时,有没有一个选项,比如id列,主键会被更改。??我真诚地怀疑有,因为它不是要更改的,但我唯一可以肯定的是,我不知道有什么办法。