I have a temp table with the following structure which gets populated with around 20k row of data (from another join query and populated in advance)
tempTable:
process_id | order_id |
---|---|
123 | 456 |
Now, I want to be able to use the above data to update another table which has the following scheama.
masterTable:
process_id | order_id |
---|---|
123 | NULL |
So that, order_id 123 of the masterTable will be updated with 456.
I also want to be able to roll back the update if needed later.
For this, I can think of two approaches.
-
a simple update, like below
update masterTable set order_id = t.order_id from masterTable as m join @tempTable as t on m.process_id = t.process_id
-
write a Stored Procedure, which will loop over every row in the tempTable and update the masterTable.
CREATE PROCEDURE UpdateMasterTableProcessID AS BEGIN -- Declare variables to hold the values from the tempTable DECLARE @order_id INT; DECLARE @process_id INT; -- Declare a cursor for iterating over the tempTable DECLARE cur CURSOR FOR SELECT order_id, process_id FROM tempTable; -- Open the cursor OPEN cur; -- Fetch the first row from the cursor FETCH NEXT FROM cur INTO @order_id, @process_id; -- Loop through the result set WHILE @@FETCH_STATUS = 0 BEGIN -- Update the masterTable for the current row UPDATE masterTable SET process_id = @process_id WHERE order_id = @order_id; -- Fetch the next row from the cursor FETCH NEXT FROM cur INTO @order_id, @process_id; END; -- Close and deallocate the cursor CLOSE cur; DEALLOCATE cur; END;
Can somebidy tell me what would be the better approach between these two pls?
I think SP may be better as I can then add new columns called Updated and keep it updated, so that I know which record has been updated and which isn’t. but I want to evaluate the pros and cons of each approach given I would be updating around 20k records.
mano tmika is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3