I have such a variable in the procedure:

DECLARE @Items TABLE (ItemId UNIQUEIDENTIFIER, OldItemId UNIQUEIDENTIFIER) 

I filled it with data:

 INSERT @Items (ItemId, OldItemId) SELECT NEWID(), t1.ItemId FROM UsersItems t1 WHERE t1.IsActual = 1 

I also have an ItemsToUsers table, which contains the following data:

 CREATE TABLE ItemsToUsers ( ItemId UNIQUEIDENTIFIER NOT NULL, UserId UNIQUEIDENTIFIER NOT NULL, CONSTRAINT PK_ItemsToUsers PRIMARY KEY(ItemId, UserId) ) 

I need to replace all the ItemId in the ItemsToUsers table with the ItemId from @Items , where ItemsToUsers . ItemId = @Items . OldItemId .

I do not quite understand how to do this. I do this, but this is not correct:

 UPDATE ItemsToUsers SET ItemId = @Items.ItemId WHERE ItemId = @Items.OldItemId 

I understand that you need to make a condition, something like:

 UPDATE ItemsToUsers SET ItemId = (SELECT t2.ItemId FROM ItemsToUsers t1 JOIN @Items t2 ON t1.ItemId = t2.OldItemId) WHERE ItemId = @Items.OldItemId 

How to make it right?

    1 answer 1

    Your last version contains almost everything you need, you need only a small amendment:

     UPDATE t1 SET ItemId = t2.ItemId FROM ItemsToUsers t1 JOIN @Items t2 ON t1.ItemId = t2.OldItemId 
    • Thank you for what you need) Everything turned out to be much easier than I thought) - Sanvirtus