A union of curiosity and data science

Knowledgebase and brain dump of a database engineer


SQL Server Cursor Example

 
Cursor example for looping through items in a temp table.
 
 
Cursor Example

create table #sandbox

(id int identity(1,1), val varchar(128))

insert into #sandbox (val)

select 'SQL is Fun'

insert into #sandbox (val)

select 'T-SQL is the Funnest'

insert into #sandbox (val)

select 'Yea, but cursors are dangerous'

GO

 

declare @data varchar(128)

 

Declare sandy_cursor cursor

      FOR Select val from #sandbox

 

      open sandy_cursor

 

      fetch next from sandy_cursor into @data

 

      while @@fetch_status = 0

      begin

            print @data

            fetch next from sandy_cursor into @data

      end

 

close sandy_cursor

deallocate sandy_cursor