Function to Split Comma separated string to Integer
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')

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)
Tags: function t-sql, scripts
Trackback from your site.
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. [...]
Setting and Changing Collation – SQL Server 2008 « Blog
| #
[...] to sql-articles.comRead more: http://sql-articles.com/articles/dba/how-to-change-server-collation-in-sql-server-2008/#ixzz1pu2S8XW… Like this:LikeBe the first to like this [...]
VidhyaSagar
| #
Naveen,
I’ll check this out and get back to you.
balakiran
| #
Thanks man, Very simple & easy to understand !!!!