Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server stored procedure - SELECT statement then use results in INSERT statement

I am writing a stored procedure that will get results from one table then copy them to another. It isn't an exact match, I'm changing 1 column and ignoring another. There are 5 columns and on average 3-5 results if that is relevant.

I basically need to:

SELECT * FROM sometable WHERE somecolumn = 1

Then for every result

INSERT INTO anothertable (a,b,c) VALUES (@a, @b, @c)

What is the best way to do this within a stored procedure?

like image 984
MattP Avatar asked Sep 10 '26 15:09

MattP


1 Answers

You can do this in one statement:

INSERT AnotherTable (a, b, c)
SELECT a, b, c
FROM SomeTable
WHERE SomeColumn = 1

Wherever possible, avoid doing things in loops/cursors/RBAR (Row By Agonizing Row) and instead try to think in SET-based approaches like above.

like image 110
AdaTheDev Avatar answered Sep 13 '26 09:09

AdaTheDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!