Introduction: In this article I am going to
share how to convert or split large comma separated string into table rows using our own created custom function in sql server.
In
previous articles i explained How to get column values as comma separated list in sql server and Concatenate first,middle and last name in Sql Server and Multiple queries to get second,third,fourth or nth highest salary of employee and Difference between temporary table and table variable and Copy all data from one database table to another database table
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
|
Now over to you:
If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..