James Radford
James Radford

Reputation: 1855

iterating over a temporary table and for each row update another tables row in sql

i have a temporary table with two columns in it, shown below:

CREATE TABLE #Temp1 (
    id VARCHAR(50),
    gid int NULL
)

My problem is that I need to iterate over each row in #Temp1 and update another table, something like below although I'm struggling how to do this in an sql script? Can anyone provide this for me?

foreach(row in #Temp1)
{
  UPDATE MyTable SET Column1 = row.gid WHERE id = row.id
}

Many thanks, James

Upvotes: 1

Views: 180

Answers (2)

M.Ali
M.Ali

Reputation: 69504

You can simply do a join between the tables something like this

UPDATE M 
SET M.Column1 = T.gid 
FROM #Temp1 T INNER JOIN MyTable M
ON T.id = M.id

Upvotes: 4

David Garrison
David Garrison

Reputation: 2880

I think this should do what you need

Update MyTable 
Set column1 = (Select gid FROM #Temp1 t WHERE t.Id = MyTable.Id)

Upvotes: 0

Related Questions