Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 request example on creating a cursor to loop through records [closed]

Does any have experience in creating cursor to loop through a bunch of records? If you do can you provide me with a basic example. Thanks

like image 466
user1583384 Avatar asked Aug 08 '12 01:08

user1583384


People also ask

How do you write a cursor for a loop in SQL Server?

Normally, when we need data looping, we use either "Cursors" or "While loop" in SQL Server. Both are used with multiple rows to give decisions on a row-by-row basis. Cursors - Cursor is a database object used by applications to manipulate the data in a set on a row-by-row basis.

Which SQL command is used to iterate through each row in a cursor?

For more information on cursors, also take a look at the free SQL query training provided by Steve Stedman. In SQL Server the cursor is a tool that is used to iterate over a result set, or to loop through each row of a result set one row at a time.


1 Answers

declare cur cursor for 
select id from tbl 
open cur
declare @id int
fetch next from cur into @id
while (@@FETCH_STATUS = 0)
begin
    print(@id)
    fetch next from cur into @id
end
close cur
deallocate cur

-- just replace "tbl" with your table name and "id" with your field name
-- and do whatever you want in begin-end block (now it simply prints the id of each record)
like image 155
Grisha Weintraub Avatar answered Sep 29 '22 10:09

Grisha Weintraub