Question

I have a table as follows:

create table temp_cte1(id int primary key,name nvarchar(max))

And another table as follows:

create table temo_cte2(id int,name nvarchar(max)),constraint fk_id foreign key(id) references temp_cte1(id)

Let us say I have the following values in both table:

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')

Now, as long as I use the cte to update the 'name' column of any table, it works fine. But when I am trying to update the id, i am getting an error as the foreign key has been violated.

Query that is working fine:

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

But what I need.. to do is something like this:

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'

Any help with this??? Thanks in advance.

Était-ce utile?

La solution

I think that should work for you:

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?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top