Create Split Function In SQL

Create table valued function as below code

SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
CREATE FUNCTION [dbo].[Split]
(
    @RowData nvarchar(MAX),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table
(
    Id int identity(1,1),
    Data nvarchar(100)
)
AS  
BEGIN
    Declare @Cnt int
    Set @Cnt = 1

    While (Charindex(@SplitOn,@RowData)>0)
    Begin
        Insert Into @RtnValue (data)
        Select
            Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))

        Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
        Set @Cnt = @Cnt + 1
    End
    
    Insert Into @RtnValue (data)
    Select Data = ltrim(rtrim(@RowData))
    DELETE FROM @RtnValue WHERE ISNULL(Data,”)=”

    Return
END
GO

Now i want to split my string ‘a,b,c,d,e,f,g,h,i,j’. write query as below

SELECT * FROM dbo.Split(‘a,b,c,d,e,f,g,h,i,j’,’,’)

You will get result as below image

sql_3

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s