Sunday, 25 February 2018

Example of Cursor, While Loop and Split comma all together in SQL SERVER

Declare @SBUCode2 varchar(50)                       
Declare @Percentage2 varchar(50)   
Declare @CONTROLID2 int 
Declare @countSBU int,@countPER int 
Declare @SBU int,@PER numeric 
Declare sBUCur cursor local scroll for Select CONTROLID,SBUCode,Percentage from #tblAcVoucherFinal where CONTROLID= @CONTROLID                     
open sBUCur                       
fetch next from sBUCur into @CONTROLID2,@SBUCode2,@Percentage2                       
while not @@fetch_status <> 0                       
Begin 

--here its getting count of SBU after splitting commas 
Select @countSBU= count(*) from dbo.split(@SBUCode2,',') 
 
declare @I int=0 
WHILE @I <= @countSBU-1 
BEGIN 
--here its getting value of SBU n Percentage as per ID from Split Function and Saving in table 
Select @SBU=Value from dbo.split(@SBUCode2,',') where id=@I 
Select @PER=Value from dbo.split(@Percentage2,',') where id=@I 
 
Insert into tblAcvoucherDetails_SBU (VNo,SBUCode,Percentage,TransDate,UserID)                                 
Values(@VNo,@SBU,@PER ,@Trans_Date,@UserID) 
 
SET @I = @I + 1   
END 
 
fetch next from sBUCur into @CONTROLID2,@SBUCode2,@Percentage2                     
End                       
close sBUCur                       
deallocate sBUCur          

No comments:

Post a Comment