-1
我有一個表,如下所示:更新使用CTE在兩個表
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更新任何表的'名稱'列,它就可以正常工作。 但是,當我試圖更新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'
任何幫助???提前致謝。
請問_why_你需要更新的主鍵?這聽起來像一個不太好的主意,特別是用外鍵引用它。 –
無論這個想法可能會發生什麼,問題是我辦公室的老年人想要這樣做。 – vstandsforvinay
[This answer](http://stackoverflow.com/a/2499328/477878)處理這種情況,但我不能強調,_changing主鍵是一個非常糟糕的主意_。 –