Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to loop through all results in a table

Author  Topic 

gregoryagu
Yak Posting Veteran

80 Posts

Posted - 2008-07-15 : 18:42:28
What I need to do is a select statement, and then loop through each row and do an insert based on the data in the first result set:

SELECT DISTINCT [userid] from Registry
where [key] = 'HomePageTab'


then for each row

INSERT INTO REGISTRY (userid, key, value) VALUES (from first query, 'HomePageTab', 'MyStringValue'

What is the usual way to do this in SQL Server 2005? This will all be inside a stored procedure.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-07-15 : 18:44:39
No looping required or recommended.

INSERT INTO REGISTRY (userid, key, value)
SELECT DISTINCT [userid], 'HomePageTab', 'MyStringValue'
from Registry
where [key] = 'HomePageTab'

Modify the select statement to what you want, I just did a copy/paste.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

chamin.Lanerole
Starting Member

2 Posts

Posted - 2008-07-16 : 02:33:29
tkizer is correct. and for complex transactions u can use cursors also. see sql server cursors.
Go to Top of Page

gregoryagu
Yak Posting Veteran

80 Posts

Posted - 2008-07-16 : 10:29:06
Great, thanks very much!
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-07-16 : 12:33:56
quote:
Originally posted by chamin.Lanerole

tkizer is correct. and for complex transactions u can use cursors also. see sql server cursors.



It should be said though to avoid cursors in almost all situations, if possible.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -