Split Function in SQL Server

Hello everyone,

In this article, I will try to give information about the Split function in SQL Server.

In SQL Server, in some cases, you may want to show the comma strings you have in a tabular form by separating them with Id.

You can easily do this using the code below.

CREATE FUNCTION fn_Split
(
    @delimited NVARCHAR(MAX),
    @delimiter NVARCHAR(100)
)
RETURNS @t TABLE
(
    Id INT IDENTITY(1, 1),
    Val NVARCHAR(MAX)
)
AS
BEGIN
    DECLARE @xml XML;
    SET @xml = N'<root><r>' + REPLACE(@delimited, @delimiter, '</r><r>') + '</r></root>';

    INSERT INTO @t
    (
        Val
    )
    SELECT r.value('.', 'varchar(max)') AS item
    FROM @xml.nodes('//root/r') AS records(r);

    RETURN;
END;
GO

--Using the Function

SELECT * FROM dbo.fn_Split('2,3,6,5,8,9,99',',')

Split Function in SQL Server

As you can see, we have separated the comma strings with Id.

Good luck to everyone in business and life.

112 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!