Cari Blog Ini

28 Oktober 2013

Example How To Select Multiple Column in SQL Using Cursor





1. Example Table



2. Try to run the below query,
------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------
declare @tranrefno varchar(50)
,@oldpolicyno varchar(17)
,@dateissue datetime


declare cur cursor for 
select tranrefno,oldpolicyno,dateissue 
from PolicyRegTrx_1 
where dateissue <='2006-01-05' 
order by dateissue,tranrefno


open cur
fetch next from cur into @tranrefno,@oldpolicyno,@dateissue
while @@fetch_status = 0
begin
if @dateissue='2006-01-01'
  print convert(varchar,@dateissue)+'--- '+@tranrefno +'--- '+@oldpolicyno
else
  print '---OTHERS--- '+ cast(@dateissue as varchar)+' ---'+@tranrefno+' ---'+@oldpolicyno
fetch next from cur into @tranrefno,@oldpolicyno,@dateissue
end

close cur
deallocate cur
------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------




3. The results, is