Wednesday, 26 June 2013

split comma separated string in sql server 2012

CREATE FUNCTION dbo.fnStringSplit
(
    @T VARCHAR(8000)='Where,there,is,a,will,there,is,a,way'
  , @Delimiter CHAR(1) = ','
)
RETURNS @List TABLE (Value VARCHAR(8000))
AS
BEGIN
     SET @T =@T+ @Delimiter

     ;WITH MyCTE(Start,[End]) AS(

     SELECT 1 AS Start,CHARINDEX(',',@T,1) AS [End]
     UNION ALL
     SELECT [End]+1 AS Start,CHARINDEX(',',@T,[End]+1)AS [End] from MyCTE where [End]<LEN(@T)
     )

     insert into @List
     Select SUBSTRING(@T,Start,[End]-Start)from MyCTE;

     RETURN;
END



CREATE FUNCTION dbo.fnStringSplit
(
    @sInputList VARCHAR(8000)
  , @sDelimiter VARCHAR(8000) = ','
)
RETURNS @List TABLE (Value VARCHAR(8000))
AS
BEGIN
    DECLARE @sItem VARCHAR(8000)
    WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
     BEGIN
     SELECT
      @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
      @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))

     IF LEN(@sItem) > 0
      INSERT INTO @List SELECT @sItem
     END

    IF LEN(@sInputList) > 0
     INSERT INTO @List SELECT @sInputList
    RETURN
END
GO

No comments:

Post a Comment