T-SQL Split Function : Split Field By a Delimiter

Posted by on Feb 20, 2012 in SQL Server, T-SQL | One Comment
Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Hi,

Today one of my colleagues in company faced a problem, He wants to split a text field by a delimiter character.

This motivate me to write a Split function for my own use and put it here for help others.

Suppose that our Primary Data is like this image and delimited by single slash ( / )


I created a Scalar Value T-SQL Function to create the string to be used in select statement, so the function will return a string which should be used in a select statement and the function itself doesn’t split data. result of this function should be used in a dynamic t-sql to return result as expected.

This is script of the function:

— ================================================
— This Function will generate script to be used
— in a select statement and fetch every delimited
— as a column
— Use it in this way: (Example)
—  declare @sql varchar(max)
— set @sql=’select ‘+dbo.SplitFieldByDelimiter(‘ZoneName’,’/’,8)
— +’ from [TVNZ_NDS].[Staging].[tmpImpressionExtract]’

— exec (@sql)
 — ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
— =============================================
— Author:        Reza Rad
— Version:     1.0
— Create date: 21/02/2012
— Description:    To Split a Delimited field by a Delimiter
— =============================================
CREATE FUNCTION dbo.SplitFieldByDelimiter
(
    @fieldname varchar(max)
    ,@delimiter varchar(max)
    ,@delimiter_count int
)
RETURNS varchar(max)
AS
BEGIN
    — variable declaration
    declare @first_index varchar(max)
    ,@next_index varchar(max)
    ,@sql_statement varchar(max)
    ,@term_statement varchar(max)
    ,@length varchar(max)
    ,@iterator int

    — initialization
    set @next_index=-1
    set @iterator=1
    set @sql_statement=’ ‘

    — code
    while(@iterator<=@delimiter_count)
    begin
        set @first_index=@next_index+’+1′
        set @next_index=’CHARINDEX(”’+@delimiter+”’,’+@fieldname+’,’+@first_index+’)’
        if (@iterator=@delimiter_count)
        begin
        set @next_index=’LEN(‘+@fieldname+’)+1′
        end
        set @length=@next_index+’-(‘+@first_index+’)’
        set @term_statement=’SubString(‘+@fieldname+’,’+@first_index+’,’+@length+’)’
        set @term_statement=’case when ‘+@next_index+’>0 then ‘+@term_statement+’ else ”nothing” end as Column’+CONVERT(varchar(max),@iterator)
        if (@iterator=1)
        begin
            set @sql_statement=@term_statement
        end
        else
        begin
            set @sql_statement=@sql_statement+’, ‘+@term_statement
        end

        set @iterator=@iterator+1
    end


    — Return the result of the function
    RETURN @sql_statement

END
GO

and This is they way we use it :

declare @sql varchar(max)
set @sql=’select top 1000 ‘+dbo.SplitFieldByDelimiter(‘DelimitedText’,’/’,8)
+’ from [TmpDataTable]’

exec (@sql)

So result will be like this :


In this version of Split function you need to enter number of occurrence of delimiter as function parameters, but I will solve it soon and publish version 2 without need for occurrence.

Hope it helps you all 🙂

P.S:

I created a CodePlex project for this Split function to work on it further.

CodePlex T-SQL Split url is :

http://tsqlsplit.codeplex.com/

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail
rssyoutuberssyoutube
Reza Rad on FacebookReza Rad on LinkedinReza Rad on TwitterReza Rad on Youtube
Reza Rad
Trainer, Consultant, Mentor
Reza Rad is a Microsoft Regional Director, an Author, Trainer, Speaker and Consultant. He has a BSc in Computer engineering; he has more than 20 years’ experience in data analysis, BI, databases, programming, and development mostly on Microsoft technologies. He is a Microsoft Data Platform MVP for eight continuous years (from 2011 till now) for his dedication in Microsoft BI. Reza is an active blogger and co-founder of RADACAD. Reza is also co-founder and co-organizer of Difinity conference in New Zealand.
His articles on different aspects of technologies, especially on MS BI, can be found on his blog: https://radacad.com/blog.
He wrote some books on MS SQL BI and also is writing some others, He was also an active member on online technical forums such as MSDN and Experts-Exchange, and was a moderator of MSDN SQL Server forums, and is an MCP, MCSE, and MCITP of BI. He is the leader of the New Zealand Business Intelligence users group. He is also the author of very popular book Power BI from Rookie to Rock Star, which is free with more than 1700 pages of content and the Power BI Pro Architecture published by Apress.
He is an International Speaker in Microsoft Ignite, Microsoft Business Applications Summit, Data Insight Summit, PASS Summit, SQL Saturday and SQL user groups. And He is a Microsoft Certified Trainer.
Reza’s passion is to help you find the best data solution, he is Data enthusiast.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *