CREATE FUNCTION dbo.DistinctList(@List VARCHAR(MAX),@Delim CHAR)RETURNS
VARCHAR(MAX)AS
BEGIN
DECLARE @ParsedList TABLE(Item VARCHAR(MAX)
)DECLARE @list1 VARCHAR(MAX), @Pos INT, @rList VARCHAR(MAX)SET @list = LTRIM(RTRIM(@list)) + @DelimSET @pos = CHARINDEX(@delim, @list, 1)WHILE @pos > 0BEGIN
SET @list1 = LTRIM(RTRIM(LEFT(@list, @pos - 1)))IF @list1 <> ''INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX)))SET @list = SUBSTRING(@list, @pos+1, LEN(@list))SET @pos = CHARINDEX(@delim, @list, 1)END
SELECT @rlist = COALESCE(@rlist+',','') + itemFROM (SELECT DISTINCT Item FROM @ParsedList) tRETURN @rlistENDGOSELECT dbo.DistinctList('342,34,456,34,3454,456,aa,bb,cc,aa',',')DistinctList
GO
VARCHAR(MAX)AS
BEGIN
DECLARE @ParsedList TABLE(Item VARCHAR(MAX)
)DECLARE @list1 VARCHAR(MAX), @Pos INT, @rList VARCHAR(MAX)SET @list = LTRIM(RTRIM(@list)) + @DelimSET @pos = CHARINDEX(@delim, @list, 1)WHILE @pos > 0BEGIN
SET @list1 = LTRIM(RTRIM(LEFT(@list, @pos - 1)))IF @list1 <> ''INSERT INTO @ParsedList VALUES (CAST(@list1 AS VARCHAR(MAX)))SET @list = SUBSTRING(@list, @pos+1, LEN(@list))SET @pos = CHARINDEX(@delim, @list, 1)END
SELECT @rlist = COALESCE(@rlist+',','') + itemFROM (SELECT DISTINCT Item FROM @ParsedList) tRETURN @rlistENDGOSELECT dbo.DistinctList('342,34,456,34,3454,456,aa,bb,cc,aa',',')DistinctList
GO
No comments:
Post a Comment