Thursday, October 20, 2011

Inserting Multiple records in sql using while loop

CREATE proc usp_InsertMultiple

as      

Declare @UserIdNew int     
Declare @CountTo int=0           
 Declare  @char int   
Declare @userIds VARCHAR(MAX)      
SELECT @userIds = COALESCE(@userIds+',' ,'') +CAST(UserId  as varchar(Max)) from TblUsers       
 Set @userIds=@userIds+','   
SELECT @userIds   
 if(@userIds <>'')       
 begin       
 while(CHARINDEX (',',@userIds)>0)       
 begin    
        set  @char=  CHARINDEX (',',@userIds)   
        print @char   
        set @UserIdNew=LTRIM(RTRIM(substring(@userIds,1,CHARINDEX(',',@userIds)-1)))       
        insert into tbl01 (UserId) values(@UserIdNew)    
        set @userIds=SUBSTRING(@userIds,charindex(',',@userIds)+1,LEN(@userIds))       
        set @CountTo=@CountTo+1         
        set @UserIdNew=''     
 end       
end      
       
      
                          

No comments:

Post a Comment