Function to Split Comma separated string to Integer

Written by Deepak. Posted in Scripts

There are cases where we need to pass the input parameter to the stored procedure as a comma-separated string in order to avoid multiple db calls from happening. This helps in reducing the db calls thereby reducing the load on the db server.

The below function will split the given comma-separated string into integers and process the results.

IF EXISTS(SELECT name FROM sys.objects WHERE name='fnSplitBigInt' AND type='TF')

DROP FUNCTION [dbo].[fnSplitBigInt] 

GO


CREATE FUNCTION [dbo].[fnSplitBigInt] 

(

    -- Add the parameters for the function here

    @input nvarchar(4000)

)

RETURNS @retBigint TABLE 

(

    [Value] [bigint] NOT NULL

)

AS

BEGIN


    DECLARE @bigint nvarchar(100)

    DECLARE @pos int


    SET @input = LTRIM(RTRIM(@input))+ ',' -- TRIMMING THE BLANK SPACES

    SET @pos = CHARINDEX(',', @input, 1) -- OBTAINING THE STARTING POSITION OF COMMA IN THE GIVEN STRING


    IF REPLACE(@input, ',', '') <> '' -- CHECK IF THE STRING EXIST FOR US TO SPLIT

    BEGIN

        WHILE @pos > 0

        BEGIN

            SET @bigint = LTRIM(RTRIM(LEFT(@input, @pos - 1))) -- GET THE 1ST INT VALUE TO BE INSERTED

            IF @bigint <> ''

            BEGIN

                INSERT INTO @retBigint (Value) 

                VALUES (CAST(@bigint AS bigint)) 

            END

            SET @input = RIGHT(@input, LEN(@input) - @pos) -- RESETTING THE INPUT STRING BY REMOVING THE INSERTED ONES

            SET @pos = CHARINDEX(',', @input, 1) -- OBTAINING THE STARTING POSITION OF COMMA IN THE RESETTED NEW STRING


        END

    END    

    RETURN

    

END

The following is an sample output result set of that function

SELECT * FROM dbo.fnSplitbigint('12345,87612,988473')

integer_split_function

Method2

The 2nd method is a much more simpler and optimal way of splitting the comma separated string

DECLARE @xml AS XML,@str AS VARCHAR(100),@delimiter AS VARCHAR(10)
SET @str='12345,87612,988473'
SET @delimiter =','
SET @xml = CAST(('<X>'+REPLACE(@str,@delimiter ,'</X><X>')+'</X>') AS XML)
SELECT N.value('.', 'varchar(50)') AS value FROM @xml.nodes('X') AS T(N)

VN:F [1.9.17_1161]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.17_1161]
Rating: +1 (from 1 vote)

Tags: ,

Trackback from your site.

Deepak

Microsoft Most Valuable Professional (MVP) award-winning Database Designer with 5 years of experience in designing, administering, developing & performance tuning relational databases and data warehouse. I possess strong leadership skills experience by serving as the Chapter Leader of Professional Association for SQL Server (PASS) which has around 50 members. I am passionate about solving business problems using my technical skills and hence I am interested in the field of Technology Consulting in Information Management.

Leave a comment

*

Recent Comments

Amit Bhatt

|

Hi Deepak,

Thanks for such a nice article.

You missed one thing to add in code:
@article = ‘all’,

Hence the script will be like this:
EXEC sp_addsubscription
@publication = ‘mypublication’,
@article = ‘ALL’,
@subscriber = ‘Subscriberservername’,
@destination_db = ‘mydestinationdbname’,
@reserved=’Internal’

Error 18486 | Platformblog

|

[...] SQL-Articles » Troubleshooting Login failed Error 18456This is one of the infamous error message (and number) that most of the DBAs …. 18486. Login failed for user ‘%.*ls’ because the account is currently locked out. [...]

VidhyaSagar

|

Naveen,
I’ll check this out and get back to you.

balakiran

|

Thanks man, Very simple & easy to understand !!!!