Thursday, 8 November 2012

How to Create Cursor in MSSQL and Add Column as Row in Table


How to Create Cursor in MSSQL and Add Column as Row in Table from another table -:

Step-1 -:

 I create two table from in which
I have column to match
and 
Another table from which i want to match

I use cursor to match the column valum in another table row value.


create table #tmpHeads  
(  
HeadID nvarchar(100),  
HeadName nvarchar(100)  

 declare @sumallheadwise nvarchar(max)=''  
declare @strQryHeadDetails nvarchar(max)
set @strQryHeadDetails=''  
declare @HDName nvarchar(50)  
declare @HDId nvarchar(50)  
  
insert into #tmpHeads select HeadId, HeadName from FeeHead  
declare cur cursor  for select HeadName, HeadID  from FeeHead where HeadID in (select FeeHeadID from FeeReciept_Master)  
--declare cur cursor  for select HeadName ,HeadId from #tmpHeads  
open cur fetch next from cur into  @HDName, @HDId  
while @@FETCH_STATUS=0  
begin  
exec ('alter table #tmpHeadsdetail add [' + @HDName + '] decimal(18,2) default 0.00 ' )  
  
if(@strQryHeadDetails='')  
begin  
set @strQryHeadDetails = @strQryHeadDetails + 'sum((case when FeeHeadID='''+@HDId +''' then RecievedAmount else 0 end )) as [' + @HDName +'] '  
set @sumallheadwise = @sumallheadwise + 'sum(['+@HDName +']) as [' + @HDName +'] '  
  
end  
else  
begin  
set @strQryHeadDetails = @strQryHeadDetails + ' , sum((case when FeeHeadID='''+@HDId +''' then RecievedAmount else 0 end )) as [' + @HDName +'] '  
set @sumallheadwise = @sumallheadwise + ', sum(['+@HDName +']) as [' + @HDName +'] '  
  
end  
  
fetch next from cur into  @HDName, @HDId  
end  

 --select @strQryHeadDetails 

close cur  
deallocate cur 


select * from #tmpHeads

Note- We always d
eallocate the Cursor but not drop the cursor
If you are running this code then first drop the temporary table from the memory as-

drop table  #tmpHeads


0 comments:

Post a Comment