DCSIMG
T-SQL Split function - Itai Goldstein

T-SQL Split function

During one of the projects I worked on, I had to parse a text which was passed from the application in my T-SQL code. I found that T-SQL had no built-in string system function for this operation, which I find rather useful, especially in cases you need to perform some batch based operations (which helps accelerate your application performance by reducing round trips to the DB).

So I came up with the following solution:

CREATE FUNCTION [dbo].[Split]
(    
    @RowData NVARCHAR(MAX),
    @Delimeter NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE 
(
    ID INT IDENTITY(1,1),
    Data NVARCHAR(MAX)
) 
AS
BEGIN 
    DECLARE @Iterator INT
    SET @Iterator = 1

    DECLARE @FoundIndex INT
    SET @FoundIndex = CHARINDEX(@Delimeter,@RowData)

    WHILE (@FoundIndex>0)
    BEGIN
        INSERT INTO @RtnValue (data)
        SELECT 
            Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))

        SET @RowData = SUBSTRING(@RowData,
                @FoundIndex + DATALENGTH(@Delimeter) / 2,
                LEN(@RowData))

        SET @Iterator = @Iterator + 1
        SET @FoundIndex = CHARINDEX(@Delimeter, @RowData)
    END
    
    INSERT INTO @RtnValue (Data)
    SELECT Data = LTRIM(RTRIM(@RowData))

    RETURN
END

Note that this implementation uses DATALENGTH function instead of the LEN function, and that is due to the fact that LEN doesn’t consider the leading spaces in the given string variable – this can harm the parsed result. Another difference between DATALENGTH and LEN is that DATALENGTH returns the result as the number of bytes used where LEN returns the result as number of characters, and that is the reason we should divide the DATALENGTH result with 2.

Here is an example of how to use the Split function:

DECLARE @Str NVARCHAR(MAX)
SELECT @Str = 'This#$#is#$#my#$#test'

SELECT *
FROM   [dbo].[Split] (@Str, '#$#')

And here are the results:

 image

Summary

In this post I reviewed my implementation for T-SQL string Split function which you may find useful when parsing strings in T-SQL, especially in cases you would like to improve your application performance by doing some batch based operations.

Hope you’ll find it useful.

Published Sunday, February 01, 2009 3:54 PM by itai

Comments

# T-SQL Split function - Itai Goldstein

Thank you for submitting this cool story - Trackback from DotNetShoutout

Monday, February 02, 2009 1:25 AM by DotNetShoutout

# re: T-SQL Split function

another way using a CTE:

CREATE FUNCTION [dbo].[Split]

(    

   String nvarchar(max), @Delimiter nvarchar(max) = ','

)

RETURNS TABLE AS

RETURN

  WITH csvtbl(start, stop) AS (

    SELECT start = convert(bigint, 1),

           stop = charindex(@Delimiter, @String + @Delimiter)

    UNION ALL

    SELECT start = stop + 1,

           stop = charindex(@Delimiter,

                            @String + @Delimiter, stop + 1)

    FROM   csvtbl

    WHERE  stop > 0

 )

 SELECT ltrim(rtrim(substring(@String, start,

                     CASE WHEN stop > 0 THEN stop - start ELSE 0 END)))

        AS Item

 FROM   csvtbl

 WHERE  stop > 0

;

Monday, February 02, 2009 7:34 PM by BxB

# re: T-SQL Split function

I've always wondered why no split function was included, natively.  It's such a useful function.

Monday, February 02, 2009 10:38 PM by Sean

# re: T-SQL Split function

Great function!

helped me a lot!

Thursday, July 09, 2009 10:06 AM by Ruti

# re: T-SQL Split function

Hi Itai,

Thanks for this code,

i changed your code so i can get selected value from the string

hope it will help others

Shay

Use the Function

============

Set @DataRow = 'Data1|Data2|Data3'

Set @var=(select dbo.fn__SplitValue(@DataRow, '|', 3))

-- >>> @var=Data3

-- ================================================

-- Description: Split String and get Selected Value

================================================

Create FUNCTION [dbo].[fn__SplitValue]

(

@DataRow VARCHAR(max),     -- Full string to split

@Delimeter nvarchar(max),  -- Spliter

@PlaceId int               -- place of value in split datarow to return

)

RETURNS VARCHAR(max)

AS

BEGIN

-- Declare parameters

DECLARE @DataValue VARCHAR(max)

   DECLARE @FoundIndex INT

   DECLARE @Iterator INT = 1 -- Place finder

   SET @FoundIndex = CHARINDEX(@Delimeter,@DataRow)

   WHILE (@FoundIndex>0) -- loop splited values

   begin

       if(@Iterator=@PlaceId)

       begin

            -- found the place of selected value in string split

            Set @DataValue = LTRIM(RTRIM(SUBSTRING(@DataRow, 1, @FoundIndex - 1)))

       end

       -- goto Next value

       SET @DataRow = SUBSTRING(@DataRow, @FoundIndex + DATALENGTH(@Delimeter) / 2, LEN(@DataRow))

       SET @Iterator = @Iterator + 1

       SET @FoundIndex = CHARINDEX(@Delimeter, @DataRow)

   END

if(@Iterator=@PlaceId)

Begin

-- Last value has no Delimeter after

Set @DataValue = LTRIM(RTRIM(@DataRow))

End

-- Return the result of the function

RETURN @DataValue

END

Thursday, July 23, 2009 11:10 PM by Shay Golan

# re: T-SQL Split function

can you tell me where MAX is decalred? Is this specific to 2005?

Thursday, August 20, 2009 5:46 PM by dave

# re: T-SQL Split function

This function is really helpful. Thank you so much.

Tuesday, September 01, 2009 7:31 PM by Lucy

# re: T-SQL Split function

Hi dave,

the ability to define the variable as VARCHAR(MAX) / NVARCHAR(MAX) was added in SQL Server 2005.

you can continue reading more about it here: www.teratrax.com/.../varchar_max.html

Thursday, September 03, 2009 8:28 AM by itai

# re: T-SQL Split function

Thanks.....

You solved my problem....

Tuesday, September 08, 2009 9:59 AM by Windy

# re: T-SQL Split function

Excellent. I've added this to one of my projects with a header comment giving you credit. Thanks for sharing.

Monday, October 26, 2009 3:41 PM by Jim Carnicelli

# re: T-SQL Split function

This function works well! Thanks for posting it!

Tuesday, February 16, 2010 11:48 PM by Bebandit

# re: T-SQL Split function

Thanks for the code. Very useful.

Wednesday, May 05, 2010 11:22 AM by Omer

# re: T-SQL Split function

golden

Sunday, June 27, 2010 4:41 AM by re: T-SQL Split function

# re: T-SQL Split function

Thanks a lot. Great solution

Thursday, September 30, 2010 3:57 PM by Dave Naismith

# re: T-SQL Split function

Thankyou for the SQL Split Function ... it helped me out :-) ... cheer

Tuesday, October 05, 2010 4:57 PM by M Dicken

# re: T-SQL Split function

The following code is about 3 times faster.  Give it a try.

CREATE FUNCTION dbo.XmlDelimitedSplit

       (

       @String VARCHAR(MAX),

       @Delimiter CHAR(1)

       )

RETURNS @Return TABLE (ItemNumber INT, ItemValue VARCHAR(max))

    AS

 BEGIN

DECLARE @Xml XML;

SELECT @Xml = '<r>' + replace(@text, @delimiter, '</r><r>') + '</r>'

;

INSERT INTO @Return

SELECT ItemNumber = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),

       ItemValue = item.value('text()[1]', 'varchar(max)')

  FROM @Xml.nodes('//r') R(item)

;

RETURN

;

   END

;

--Jeff Moden

Monday, March 07, 2011 6:32 AM by Jeff Moden

# re: T-SQL Split function

This is a really helpful solution for my purposes, and easy to implement.  Thanks!

Thursday, April 14, 2011 9:33 PM by Marianne Daye

# re: T-SQL Split function

I have string that has [Error] some error 1 [error] some error 2

and the datalenght is 1319433 and it only prints out 22 lines of errors and there are over 1800 errros to report.

Any ideas

Sunday, April 24, 2011 6:18 PM by sqlqueen

#

Pingback from  

Monday, August 08, 2011 6:03 AM by TrackBack

# Transact-SQL: How do I tokenize a string? - Programmers Goodies

Pingback from  Transact-SQL: How do I tokenize a string? - Programmers Goodies

# re: T-SQL Split function

Thank you...

Thursday, September 15, 2011 2:42 PM by Shahid

# SQL Stored Procedure &#8211; Search an array of strings in a field and display the count of occurrences

Pingback from  SQL Stored Procedure &#8211; Search an array of strings in a field and display the count of occurrences

# re: T-SQL Split function

I want to split values of string into multiple columns instead of rows ... anybody has any idea ?

Tuesday, November 01, 2011 9:02 AM by Pratik

# re: T-SQL Split function

Thank you very much!

Wednesday, December 28, 2011 12:30 PM by Beddel

# re: T-SQL Split function

Very usefull function. It works fine. Thanks for that

Thursday, January 12, 2012 4:48 PM by Lukeni2

# Filtering Comma Separated Data | PHP Developer Resource

Pingback from  Filtering Comma Separated Data | PHP Developer Resource

# sql server 2000 &#8211; Spliting a column that is a variable/value pair, and assigning a var in sql | mywebsite

Pingback from  sql server 2000 &#8211; Spliting a column that is a variable/value pair, and assigning a var in sql  | mywebsite

# tsql &#8211; Spliting a column that is a variable/value pair, and assigning a var in sql | mywebsite

Pingback from  tsql &#8211; Spliting a column that is a variable/value pair, and assigning a var in sql  | mywebsite

# re: T-SQL Split function

Thanks a lot Mr. Goldstein. You made many people's life a lot easier with this piece of fantastic code of Split functionality.

Wednesday, June 27, 2012 3:25 PM by Sourav Kings

# re: T-SQL Split function

Can I only say what relief to get someone that in fact knows what theyre discussing on line.

You definitely realize how to bring a difficulty to light and work

out it crucial. The best path to ought to check this

out and appreciate this side on the story. I cant believe youre no more wide-ranging since you also definitely give out the gift.

Tuesday, August 07, 2012 11:39 AM by Hammett

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: