HI WELCOME TO KANSIRIS

CONVERT OR SPLIT COMMA SEPARATED STRING INTO TABLE ROWS IN SQL SERVER

Leave a Comment
Description: Here I will create a table valued user defined function that splits or converts  a string containing words or letters separated by comma into table rowset. 

Implementation: Let’s create a user defined function to split passed string

CREATE FUNCTION SplitString
(
            @Str NVARCHAR(MAX),
            @Separator     CHAR(1)
)
RETURNS @ResultOutput TABLE(Id INT IDENTITY(1,1), Result NVARCHAR(100))
AS
BEGIN
            DECLARE @Splitted_string NVARCHAR(4000)
            DECLARE @Pos INT
            DECLARE @NextPos INT
           
            SET @Str = @Str + @Separator
            SET @Pos = CHARINDEX(@Separator,@Str)
            WHILE (@pos <> 0)
                        BEGIN
                                    SET @Splitted_string = SUBSTRING(@Str,1,@Pos - 1)
                                    SET @Str = SUBSTRING(@Str,@pos+1,LEN(@Str))
                                    SET @pos = CHARINDEX(@Separator,@Str)
                                    INSERT INTO @ResultOutput VALUES(@Splitted_string)
                        END
            RETURN
END 

You just need to pass the string and the separator e.g. if the string have words or letters separated by comma then pass that string and the separator  ','(Comma) to the function. Similarly if the string contains the words or letters separated by space then pass the separator ' '(space) to split the string into table rows.

Using SplitString function In Query: 

--Split string by comma
SELECT Result FROM SplitString('Split,string,example,in,sql,server',',')

--Split string by pipe symbol
SELECT Result FROM SplitString('Split|string|example|in|sql|server','|')

--Split string by space
SELECT Result FROM SplitString('Split string example in sql server',' '

Query output will be as: 
Result
Split
string
example
In
Sql
server

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.