Tuesday, June 07, 2011

tsql split up a comma seperated string into a table with duplicate records removed

thanks to many similar sources on the web, I came up with my script, it splits up a comma seperated string into a table with duplicate records removed



IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Spliter]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].Spliter
GO
CREATE FUNCTION Spliter(@String varchar(max), @Delimiter char(1))
returns @temptable TABLE (items varchar(max))
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 and (select count(items) from @temptable where items = @slice)=0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
GO


SELECT i.items FROM dbo.Spliter(@tempstring,',') AS i where items not in (select comparesource from comparesourcetable)

No comments: