Articles → SQL SERVER → Cursors In SQL Server

Cursors In SQL Server






What Are Cursors?





Steps




Declare cursor_name cursor for select_Statement




Open cursor_name




fetch next from cursor_name [into variable_name]




while @@fetchstatus = 0 
begin
   // Do something fetch next 
   from
      cursor_name [into variable_name] 
end




close cursor_name




deallocate cursor_name



Example




PK_IDsName
1Name1
2Name2




Declare @con as varchar(50) 
Declare @temp as varchar(50) 
Set
   @con = '' 
   Set
      @temp = '' 
      Declare mycursor cursor for 
      select
         sName 
      from
         tbl_Test open mycursor fetch next 
      from
         mycursor into @con while @@fetch_status = 0 
         begin
      Set
         @con = @con + @temp fetch next 
      from
         mycursor into @temp 
         end
         close mycursor deallocate mycursor 
         select
            @con  





Posted By  -  Karan Gupta
 
Posted On  -  Friday, April 30, 2010

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250