Parse delimited string in a Stored procedure

Sometimes we need to pass an array to the Stored Procrdure and split the array inside the stored proc. For example, lets say there is a datagrid displaying sales orders, each sales order associated with an orderid (PK in the Sales table). If the user needs to delete a bunch of sales orders ( say 10-15 etc)..it would be easier to concatenate all the orderid's into one string like 10-24-23-34-56-57-....etc and pass it to the sql server stored proc and inside the stored proc, split the string into individual ids and delete each sales order.

There can be plenty of other situations where passing a delimited string to the stored proc is faster than making n number of trips to the server.

CREATE PROCEDURE ParseArray (@Array VARCHAR(1000),@separator CHAR(1))
AS 

BEGIN
SET NOCOUNT ON

-- @Array is the array we wish to parse
-- @Separator is the separator charactor such as a comma

        DECLARE @separator_position INT -- This is used to locate each separator character
        DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned
-- For my loop to work I need an extra separator at the end. I always look to the
-- left of the separator character for each array value

        SET @array = @array + @separator

-- Loop through the string searching for separtor characters
        WHILE PATINDEX('%' + @separator + '%', @array) <> 0 
            BEGIN
                -- patindex matches the a pattern against a string
                SELECT  @separator_position = PATINDEX('%' + @separator + '%',@array)
                SELECT  @array_value = LEFT(@array, @separator_position - 1)
                -- This is where you process the values passed.

                -- Replace this select statement with your processing
                -- @array_value holds the value of this element of the array
                SELECT  Array_Value = @array_value
                -- This replaces what we just processed with and empty string
                SELECT  @array = STUFF(@array, 1, @separator_position, '')
            END
SET NOCOUNT OFF
END

GO


posted @ Wednesday, March 28, 2007 3:36 PM

Print

Comments on this entry:

# re: Parse delimited string in a Stored procedure

Left by Dave at 4/18/2007 1:31 PM
Gravatar
How timely! I was just looking for this example - thanks for posting it - saved me hours. I will recommend your site.

# re: Parse delimited string in a Stored procedure

Left by Shawn at 5/16/2007 3:14 PM
Gravatar
would love to see an example with the delimited text coming from a field in the database. In other words instead of passing the string in as arguments to the sp, have a select in the sp that selects a field in the db that has values that are comma delimited...and then parse through that.

# re: Parse delimited string in a Stored procedure

Left by Dinakar at 5/17/2007 3:51 PM
Gravatar
It is very easy to convert the above SP to a UDF, keeping the same logic. Create a UDF that returns a table variable, put the same logic inside. Then call the UDF from your sp as

SELECT * FROM dbp.ParseArray(col1, ',')

# re: Parse delimited string in a Stored procedure

Left by Shawn at 5/21/2007 2:12 PM
Gravatar
Thanks Dinakar...I've not worked with UDF's before and under a deadline...any chance you could post the udf code for that as well?

# re: Parse delimited string in a Stored procedure

Left by Dinakar at 5/23/2007 11:21 AM
Gravatar
Pretty simple as I said:
----------
CREATE FUNCTION dbo.fnParseArray (@Array VARCHAR(1000),@separator CHAR(1))
RETURNS @T Table (col1 varchar(50))
AS
BEGIN
--DECLARE @T Table (col1 varchar(50))
-- @Array is the array we wish to parse
-- @Separator is the separator charactor such as a comma
DECLARE @separator_position INT -- This is used to locate each separator character
DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned
-- For my loop to work I need an extra separator at the end. I always look to the
-- left of the separator character for each array value

SET @array = @array + @separator

-- Loop through the string searching for separtor characters
WHILE PATINDEX('%' + @separator + '%', @array) <> 0
BEGIN
-- patindex matches the a pattern against a string
SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)
SELECT @array_value = LEFT(@array, @separator_position - 1)
-- This is where you process the values passed.
INSERT into @T VALUES (@array_value)
-- Replace this select statement with your processing
-- @array_value holds the value of this element of the array
-- This replaces what we just processed with and empty string
SELECT @array = STUFF(@array, 1, @separator_position, '')
END
RETURN
END
----------

You can call the function as:

select * from dbo.fnParseArray('a,b,c,d,e,f', ',')

# re: Parse delimited string in a Stored procedure

Left by Shawn at 5/24/2007 12:40 PM
Gravatar
awesome! thank you so much!!

# re: Parse delimited string in a Stored procedure

Left by AC77 at 8/28/2007 12:35 PM
Gravatar
Is it possible to do this with 2 input arrays and return a 2 column table?

# re: Parse delimited string in a Stored procedure

Left by Dinakar at 9/1/2007 9:52 PM
Gravatar
Function can only return one value.. You will have to call the function twice..

# re: Parse delimited string in a Stored procedure

Left by Helmut at 2/5/2008 11:30 AM
Gravatar
how would you use this passing it a field from a table... ie my table has a field (field1 varchar)
that has 1,2,3,4,56,78,999,87,65,4,32,1
how would I split that using this function??

# re: Parse delimited string in a Stored procedure

Left by Helmut at 2/5/2008 11:37 AM
Gravatar
I figured it out...
am posting for others to use:

declare @txtvar varchar(255)

select
@txtvar = field1
from
x

select *
from dbo.fnParseArray(@txtvar, ',')

# re: Parse delimited string in a Stored procedure

Left by Helmut at 2/5/2008 11:56 AM
Gravatar
well I thought I had it... that only works
with 1 row in your table...
how do i get it to work with multiple rows???




# re: Parse delimited string in a Stored procedure

Left by Josep at 8/27/2008 6:53 AM
Gravatar
Thanks very much for this great code !

# re: Parse delimited string in a Stored procedure

Left by Seed at 9/30/2008 12:05 PM
Gravatar
Hemut:

You can join the two something like this (untested):

select funcTable.*
from dbo.fnParseArray(table1.field1, ',') funcTable, x table1

# re: Parse delimited string in a Stored procedure

Left by Monster at 10/13/2008 12:09 PM
Gravatar
Thanks Dinakar..

# re: Parse delimited string in a Stored procedure

Left by Unisol at 10/14/2008 10:38 AM
Gravatar
Thanks fro the code

# re: Parse delimited string in a Stored procedure

Left by Mdot at 10/30/2008 10:35 AM
Gravatar
I need to do something just like Hemut posted above.
I tried:
select funcTable.*
from dbo.fnParseArray(table1.field1, ',') funcTable, x table1

I get an error like
The multi-part identifier "table1.field1" could not be bound.

Any suggestions?

# re: Parse delimited string in a Stored procedure

Left by Gov at 11/14/2008 6:07 AM
Gravatar
hi all
Such a nice Article.it will defenatily help other's as it's help me

# re: Parse delimited string in a Stored procedure

Left by rüya tabiri at 11/25/2008 1:26 AM
Gravatar
Thank you

# re: Parse delimited string in a Stored procedure

Left by Bhabna at 12/10/2008 12:45 PM
Gravatar
I wrote the same function to parse the field with : delimeter. But then I added 2 more lines.

Here is my code
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER FUNCTION IVR_ADMIN.fnParseArray (@Array VARCHAR(1000),@separator CHAR(1))
RETURNS varchar(8000)
AS
BEGIN
-- @Array is the array we wish to parse
-- @Separator is the separator charactor such as a comma
DECLARE @separator_position INT -- This is used to locate each separator character
DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned
-- For my loop to work I need an extra separator at the end. I always look to the
-- left of the separator character for each array value
DECLARE @newArray VARCHAR(8000)
DECLARE @map_name VARCHAR(50)

SET @array = @array + @separator

-- Loop through the string searching for separtor characters
WHILE PATINDEX('%' + @separator + '%', @array) <> 0
BEGIN
-- patindex matches the a pattern against a string
SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)
SELECT @array_value = LEFT(@array, @separator_position - 1)
-- This is where you process the values passed.
--INSERT into map_name
-- Replace this select statement with your processing
-- @array_value holds the value of this element of the array
-- This replaces what we just processed with and empty string
SELECT @map_name = MAP_NAME from IVR_ADMIN.IVR_MAPPING where MAP_ID = @array_value

SET @map_name = @map_name + @separator
SET @newArray = @newArray + @map_name
SELECT @array = STUFF(@array, 1, @separator_position, '')
END

RETURN @newArray
END








GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

I am using the parse value in MAPPING table to get MAP_NAME and then concanate all the values. But I am getting null for

SET @map_name = @map_name + @separator
SET @newArray = @newArray + @map_name

but if I use

SET @newArray = @map_name + @separator

I am getting the expected value for second statement but not the first one.

Can anybody help me as I am new to Microsoft SQL Server.

Sorry for asking this one.

-Bhabna

# re: Parse delimited string in a Stored procedure

Left by games secret at 12/22/2008 11:46 AM
Gravatar
thanks youu

# re: Parse delimited string in a Stored procedure

Left by chat at 1/4/2009 2:27 AM
Gravatar
thank you :)

# re: Parse delimited string in a Stored procedure

Left by Jeppe Andreasen at 1/25/2009 10:21 AM
Gravatar
You could probaly speed things up a bit by not calling the patIndex twice for each Iteration... like this

...

CREATE FUNCTION dbo.ParseArray (@Array varchar(2500), @separator char(1))
RETURNS @T Table (col1 varchar(50))
AS
BEGIN
--DECLARE @T Table (col1 varchar(50))
-- @Array is the array we wish to parse
-- @Separator is the separator charactor such as a comma
DECLARE @separator_position INT -- This is used to locate each separator character
DECLARE @array_value VARCHAR(1000) -- this holds each array value as it is returned
-- For my loop to work I need an extra separator at the end. I always look to the
-- left of the separator character for each array value

SET @array = @array + @separator
SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)
-- Loop through the string searching for separtor characters
WHILE @separator_position <> 0
BEGIN
-- patindex matches the a pattern against a string
SELECT @array_value = LEFT(@array, @separator_position - 1)
-- This is where you process the values passed.
INSERT into @T VALUES (@array_value)
-- Replace this select statement with your processing
-- @array_value holds the value of this element of the array
-- This replaces what we just processed with and empty string
SELECT @array = STUFF(@array, 1, @separator_position, '')
SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)
END
RETURN
END

# re: Parse delimited string in a Stored procedure

Left by Dave at 1/27/2009 11:13 AM
Gravatar
Great code, saved me a lot of time!

# re: Parse delimited string in a Stored procedure

Left by Jim at 1/28/2009 3:22 PM
Gravatar
Modified to accept a variable length delimeter:



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnParseArray] (@Array VARCHAR(MAX),@separator VARCHAR(100))
RETURNS @T Table (col1 varchar(50))
AS
BEGIN
--DECLARE @T Table (col1 varchar(50))
-- @Array is the array we wish to parse
-- @Separator is the separator charactor such as a comma
DECLARE @separator_position INT -- This is used to locate each separator character
DECLARE @array_value VARCHAR(MAX) -- this holds each array value as it is returned
-- For my loop to work I need an extra separator at the end. I always look to the
-- left of the separator character for each array value

SET @array = @array + @separator

-- Loop through the string searching for separtor characters
WHILE PATINDEX('%' + @separator + '%', @array) <> 0
BEGIN
-- patindex matches the a pattern against a string
SELECT @separator_position = PATINDEX('%' + @separator + '%',@array)

SELECT @array_value = LEFT(@array, @separator_position - 1)
-- This is where you process the values passed.
INSERT into @T VALUES (@array_value)
-- Replace this select statement with your processing
-- @array_value holds the value of this element of the array
-- This replaces what we just processed with and empty string
SELECT @array = STUFF(@array, 1, @separator_position + (LEN(@separator)-1), '')
END
RETURN
END

# re: Parse delimited string in a Stored procedure

Left by sohbet odalari at 3/7/2009 12:37 AM
Gravatar
thank you very much .

# re: Parse delimited string in a Stored procedure

Left by Sohbet at 3/7/2009 1:28 PM
Gravatar
thankss

# re: Parse delimited string in a Stored procedure

Left by Sohbet Odalari at 3/7/2009 1:29 PM
Gravatar
thanks you

# re: Parse delimited string in a Stored procedure

Left by Mirc at 3/7/2009 1:29 PM
Gravatar
thnks

# re: Parse delimited string in a Stored procedure

Left by Chat at 3/13/2009 2:03 AM
Gravatar
thank you ..

# re: Parse delimited string in a Stored procedure

Left by ligtv izle at 3/18/2009 10:36 AM
Gravatar
thank you!

# re: Parse delimited string in a Stored procedure

Left by Mynet at 3/23/2009 4:52 AM
Gravatar
thank you kanka

# Estetik

Left by Estetik at 3/24/2009 3:18 AM
Gravatar
Thanks kral

# re: Parse delimited string in a Stored procedure

Left by maç izle at 3/28/2009 3:33 PM
Gravatar
thanki kanki

# re: Parse delimited string in a Stored procedure

Left by ligtv izle at 4/6/2009 2:22 AM
Gravatar
you are my desire..

# re: Parse delimited string in a Stored procedure

Left by chat at 4/11/2009 10:42 PM
Gravatar
thank you turkish chat34 !

# re: Parse delimited string in a Stored procedure

Left by ligtv izle at 4/18/2009 10:30 AM
Gravatar
thankx you

# re: Parse delimited string in a Stored procedure

Left by chat odaları at 4/28/2009 1:45 AM
Gravatar
thank

# re: Parse delimited string in a Stored procedure

Left by justin tv at 5/4/2009 4:47 AM
Gravatar
turkish justin tv..

# re: Parse delimited string in a Stored procedure

Left by Harsh at 5/7/2009 2:14 AM
Gravatar
Good one..!!

# re: Parse delimited string in a Stored procedure

Left by Sohbet at 5/13/2009 12:24 PM
Gravatar
hallo i wish you verry succes operator

# re: Parse delimited string in a Stored procedure

Left by Zorever at 5/21/2009 11:47 PM
Gravatar
I am Passing a String in a Stored Procedure for example
'1,2,3,4,5'
and inside the stored procedure i need to remove the single quotes on the both sides of the string and to store the rest string to a variable inside the Stored Procedure
Can i apply some operation to the string

# re: Parse delimited string in a Stored procedure

Left by Edencity Chat at 5/22/2009 6:03 PM
Gravatar
thank you admin

# re: Parse delimited string in a Stored procedure

Left by tolga at 7/1/2009 5:12 PM
Gravatar
Thank You Gavur

# re: Parse delimited string in a Stored procedure

Left by sXe at 7/1/2009 5:14 PM
Gravatar
Thank YOu Foorro

# re: Parse delimited string in a Stored procedure

Left by mp3 dinle at 7/10/2009 4:51 PM
Gravatar
Thank you very mush admin cok saol

# re: Parse delimited string in a Stored procedure

Left by en güzel oyunlar at 7/10/2009 4:52 PM
Gravatar
Thank YOu cok saol very Much

# re: Parse delimited string in a Stored procedure

Left by bosch servisi at 7/10/2009 4:54 PM
Gravatar
Thank You admin

# re: Parse delimited string in a Stored procedure

Left by wéBurak at 7/10/2009 4:58 PM
Gravatar
good post, thank you for an posting. Very good..

# re: Parse delimited string in a Stored procedure

Left by hikaye at 7/16/2009 3:45 PM
Gravatar
I am Passing a String in a Stored Procedure for example
'1,2,3,4,5'
and inside the stored procedure i need to remove the single quotes on the both sides of the string and to store the rest string to a variable inside the Stored Procedure
Can i apply some operation to the string

# re: Parse delimited string in a Stored procedure

Left by aşk at 7/17/2009 2:16 PM
Gravatar
I am grateful to you for this great content.

# re: Parse delimited string in a Stored procedure

Left by Hanna at 7/22/2009 3:39 AM
Gravatar
I need to send multiple items selected from listbox to a stored procedure where stored procedure can split it into values and on the basis of these values should return record.

Thanks.

Please help me out with this.

# re: Parse delimited string in a Stored procedure

Left by Venkitesh at 8/9/2009 11:11 PM
Gravatar
Can anybody help in this requirement?i can pass number of strings seperated by a delimiter (say #).i want to seperate these strings and search for the string in a particular table in a database and return the value of another column.
Table name can be hardcoded.

Eg: i will execute the query as

EXEC search_string bob#williams#pop#king,#

Arg1: Strings to be searched(which should be seperated and searched one by one)

# re: Parse delimited string in a Stored procedure

Left by undercrim at 9/12/2009 1:08 PM
Gravatar
Thanks for the code

# re: Parse delimited string in a Stored procedure

Left by anil at 9/12/2009 1:10 PM
Gravatar
helpfull post thank you

# re: Parse delimited string in a Stored procedure

Left by gaban at 9/12/2009 1:11 PM
Gravatar
Thanks good post

# re: Parse delimited string in a Stored procedure

Left by yaprak at 9/12/2009 1:14 PM
Gravatar
what i need thank you

# re: Parse delimited string in a Stored procedure

Left by sellini at 9/12/2009 1:17 PM
Gravatar
good post thank you

# re: Parse delimited string in a Stored procedure

Left by ozer at 9/12/2009 1:22 PM
Gravatar
thnx good post

# re: Parse delimited string in a Stored procedure

Left by elite at 9/12/2009 1:25 PM
Gravatar
thank you for very good post

# re: Parse delimited string in a Stored procedure

Left by Michael Robbins at 10/7/2009 7:52 AM
Gravatar
This is great thanks really needed this.

# re: Parse delimited string in a Stored procedure

Left by remaps at 10/10/2009 12:08 PM
Gravatar
thank you i really need it

# re: Parse delimited string in a Stored procedure

Left by Domatessuyu at 10/31/2009 12:49 PM
Gravatar
CREATE PROCEDURE ParseArray (@Array VARCHAR(1000),@separator CHAR(1))

where i put ? pls help

# re: Parse delimited string in a Stored procedure

Left by Breast Lift Philadelphia at 11/19/2009 1:12 PM
Gravatar
Honestly, I have not been into this Parse delimited String or something. But I got interested in this thing. I will make some research regarding this perhaps this idea can be beneficial in my part. Thanks for posting in!

# re: Parse delimited string in a Stored procedure

Left by burning calories at 11/22/2009 11:46 AM
Gravatar
nice site thanks !!

# re: Parse delimited string in a Stored procedure

Left by Karim Kenawy at 12/21/2009 2:24 AM
Gravatar
Thanks, it worked fine.

# re: Parse delimited string in a Stored procedure

Left by sxe at 1/9/2010 6:35 AM
Gravatar
Thanks man

worked fine

# re: Parse delimited string in a Stored procedure

Left by Stejan at 1/28/2010 4:41 AM
Gravatar
Thank . Nice post

# re: Parse delimited string in a Stored procedure

Left by gagner au jeu de poker at 2/17/2010 12:29 AM
Gravatar
This information is mostly helpful in debugging the code, but it is useless after that. By setting SET NOCOUNT ON, we can disable the feature of returning this extra information. For stored procedures that contain several statements or contain Transact-SQL loops, setting SET NOCOUNT to ON can provide a significant performance boost because network traffic is greatly reduced.

# re: Parse delimited string in a Stored procedure

Left by oyunlar at 2/24/2010 8:38 AM
Gravatar
I like the 8:00 weekday starts much better than the 7:00. I think you'll see attendance number rise a bit for these weekday games.

# re: Parse delimited string in a Stored procedure

Left by Gangster Fancy Dress at 4/7/2010 4:27 PM
Gravatar
Dinakar you are an absolute gem! Excellent stuff as always. Have a great week.:D

# konya chat

Left by konya sohbet at 4/16/2010 10:00 AM
Gravatar
thnaks very good
nice mee to

# re: Parse delimited string in a Stored procedure

Left by RSA Online at 4/29/2010 6:21 AM
Gravatar
Thank you, this split function was exactly what I needed. Can't believe that such a function is not built-in.

# re: Parse delimited string in a Stored procedure

Left by Uk Chip Tuning at 5/9/2010 12:29 PM
Gravatar
Thank your for this very usefull

# re: Parse delimited string in a Stored procedure

Left by Tune My Engine at 5/9/2010 12:31 PM
Gravatar
great job

# re: Parse delimited string in a Stored procedure

Left by Uk Chip Tuning at 5/9/2010 12:32 PM
Gravatar
nice job thanks

# re: Parse delimited string in a Stored procedure

Left by syd at 5/11/2010 11:08 AM
Gravatar
This saved me today - thank you!!

# re: Parse delimited string in a Stored procedure

Left by sudoko at 5/12/2010 4:56 PM
Gravatar
yes nicely done

# re: Parse delimited string in a Stored procedure

Left by resimleri at 5/15/2010 2:32 PM
Gravatar
merci admin

# re: Parse delimited string in a Stored procedure

Left by Koncentrix at 6/11/2010 9:52 AM
Gravatar
Very usefull... works like a charm.

# re: Parse delimited string in a Stored procedure

Left by canada online at 6/16/2010 1:41 AM
Gravatar
done
I like it

# re: Parse delimited string in a Stored procedure

Left by CHAT at 6/20/2010 12:19 PM
Gravatar
Thank your yes nicely done

# re: Parse delimited string in a Stored procedure

Left by Diego at 6/25/2010 11:45 AM
Gravatar
Great! Tank you... it was so useful to me! :)

# re: Parse delimited string in a Stored procedure

Left by Canlı chat at 7/5/2010 6:51 AM
Gravatar
very good superr thank you adminn

# Cs 1.5 Sxe Hack

Left by Cs 1.5 Sxe Hack at 7/6/2010 2:47 PM
Gravatar
Thanks Great !!!

# re: Parse delimited string in a Stored procedure

Left by sking tags at 7/16/2010 10:49 PM
Gravatar
It really works good job.

# re: Parse delimited string in a Stored procedure

Left by bosch servis at 7/20/2010 1:34 AM
Gravatar
thanks youu very much ...

# reFacebook To You All facebook In This Site.

Left by facebook at 8/19/2010 1:10 AM
Gravatar
very Thanks Great !!

# re: Parse delimited string in a Stored procedure

Left by subhre at 8/19/2010 5:43 AM
Gravatar
I have the same requirement as Helmut and MDOT and can't figure out what to do.

I'm trying something like:

line 1: select a.*
line 2: from dbo.fnParseArray(x.field1, ';') a, table1 x;

where field1 is a field in table1.

I'm getting [Incorrect syntax near '.'.] error at line 2.

Any help from anyone would be hugely appreciated. Thanks guys!

# re: Parse delimited string in a Stored procedure

Left by xat sohbet at 8/28/2010 3:18 AM
Gravatar
thnx for post very nice informations.

# re: Parse delimited string in a Stored procedure

Left by rüya tabirleri at 8/30/2010 2:32 PM
Gravatar
Thank you Comments

# re: Parse delimited string in a Stored procedure

Left by Bonus casino di Internet at 9/2/2010 4:40 AM
Gravatar
If Stored Procedure is transactional then, it should roll back complete transactions when it encounters any errors. Well, that does not happen in this case, which proves that Stored Procedure does not only provide just the transactional feature to a batch of T-SQL.

Your comment:



 (will not be displayed)


 
 
 
Please add 1 and 6 and type the answer here:
 

Live Comment Preview:

 
«September»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789