Monday, July 6, 2009

Split Function in SqlServer

/**
-----------------------------------------------------------------------------------------
-- Function Name: Split
-- Function : Split String and Convert into Table
Return Type: Table
-- :
-------------------------------------------------------------------------------------------
**/

CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (RowNo INT ,Items varchar(4000))
AS


BEGIN
DECLARE @INDEX INT
DECLARE @RowNo INT
DECLARE @SLICE nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
-- ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
SELECT @RowNo=0
-- following line added 02/12/04 as null
-- values cause issues
IF @String IS NULL RETURN
WHILE @INDEX !=0


BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING

SELECT @RowNo=@ROWNO+1
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(RowNo,Items) VALUES(@RowNo,@SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK
END
RETURN
END

No comments: