Search This Blog

Wednesday, November 28, 2012

Cursor SQL Server

SQL Server > Data Types > Cursor

SQL Server statements produce a complete result set, but there are times when the results are best processed one row at a time. Opening a cursor on a result set allows processing the result set one row at a time. You can assign a cursor to a variable or parameter with a cursor data type.

Permissions default to any user that has SELECT permissions;

Syntax:

DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]
     [ FORWARD_ONLY | SCROLL ]
     [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
     [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
     [ TYPE_WARNING ]
     FOR select_statement
     [ FOR UPDATE [ OF column_name [ ,...n ] ] ]

Example:

create table #temp
(id int)
declare @p int = 0
while @p < 10
begin
       insert into #temp
       values(@p)
       set @p = @p + 1
end

select * from #temp -- return all rows
DECLARE @id int
DECLARE c CURSOR FOR
select
   id
from
  #temp
OPEN c
FETCH NEXT FROM c INTO @id
WHILE @@FETCH_STATUS = 0
BEGIN
   print @id -- scroll row by row
    FETCH NEXT FROM c INTO @id
END
CLOSE c;
DEALLOCATE c;
drop table #temp