You are on page 1of 3

Split Functionality in Sql Server to break Comma-Separated Strings into separeted rows

DECLARE @Table1 TABLE ( row int identity(1,1), [PersonID] int, [PersonName] nvarchar(50) NULL, [PersonSkillID's] nvarchar(50) NOT NULL ); DECLARE @Table2 TABLE ( [PersonID] int, [PersonName] nvarchar(50) NULL, [PersonSkillID] nvarchar(50) NOT NULL ); declare @rowcount int,@incr int set @incr=1 insert into @Table1([PersonID] ,[PersonName],[PersonSkillID's]) SELECT [PersonID] ,[PersonName],[PersonSkillID's] Set @rowcount =(select COUNT(*) from @Table1) while @incr<=@rowcount begin declare @charindex int =(select charindex(',',[PersonSkillID's]) from @Table1 where row=@incr) while @charindex>0 Begin insert into @Table2([PersonID] ,[PersonName] ,[PersonSkillID]) select [PersonID],[PersonName], case when charindex(',',[PersonSkillID's])>0 then SUBSTRING([PersonSkillID's],0, charindex(',',[PersonSkillID's])) else [PersonSkillID's] end as [PersonSkillID's] from @Table1 t where t.row=@incr update @Table1 set [PersonSkillID's]=SUBSTRING([PersonSkillID's],charindex(',',[PersonSkillID's] )+1,LEN([PersonSkillID's])) where row=@incr set @charindex=(select charindex(',',[PersonSkillID's]) from @Table1 where row=@incr) End if @charindex=0 begin insert into @Table2([PersonID] FROM [dbo].[Split_Person]

,[PersonName],[PersonSkillID]) select [PersonID] ,[PersonName], case when charindex(',',[PersonSkillID's])>0 then SUBSTRING([PersonSkillID's],0, charindex(',',[PersonSkillID's])) else [PersonSkillID's] end as [PersonSkillID's] from @Table1 t where t.row=@incr end set @incr=@incr+1 end select * from @Table2

CREATE FUNCTION dbo.Split_String(@String varchar(8000), @Delimiter char(1)) returns @returntable TABLE (items varchar(8000)) as begin declare @idx int declare @slice varchar(8000) select @idx = 1 if len(@String)<1 or @String is null return

while @idx!= 0 begin set @idx = charindex(@Delimiter,@String) if @idx!=0 set @slice = left(@String,@idx - 1) else set @slice = @String if(len(@slice)>0) insert into @returntable(Items) values(@slice) set @String = right(@String,len(@String) - @idx) if len(@String) = 0 break end return end

DECLARE @Table1 TABLE ( row int identity(1,1), [PersonID] int, [PersonName] nvarchar(50) NULL, [PersonSkillID's] nvarchar(50) NOT NULL ); insert into @Table1([PersonID] ,[PersonName],[PersonSkillID's]) SELECT [PersonID] ,[PersonName],[PersonSkillID's] FROM [dbo].[Split_Person]

declare @x varchar(50) declare @rowcount int,@incre int declare @tab table (row int,name varchar(50),[PersonSkillID] varchar(10)) set @rowcount=(select COUNT(*) from @Table1) set @incre=1 while @incre<=@rowcount begin set @x= (select [PersonSkillID's] from @Table1 where row=@incre) insert @tab (row,[PersonSkillID]) select @incre,items from Split_String(@x,',') set @incre=@incre+1 end --select * from @tab select t1.PersonID,t1.PersonName,t.PersonSkillID from @tab t join @Table1 t1 on t1.row=t.row

You might also like