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

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

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

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

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

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

awesome! thank you so much!!

# re: Parse delimited string in a Stored procedure

Left by AC77 at 8/28/2007 12:35 PM

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

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

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

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

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

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

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

Thanks Dinakar..

# re: Parse delimited string in a Stored procedure

Left by Unisol at 10/14/2008 10:38 AM

Thanks fro the code

# re: Parse delimited string in a Stored procedure

Left by Mdot at 10/30/2008 10:35 AM

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

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

Thank you

# re: Parse delimited string in a Stored procedure

Left by Bhabna at 12/10/2008 12:45 PM

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

thanks youu

# re: Parse delimited string in a Stored procedure

Left by chat at 1/4/2009 2:27 AM

thank you :)

# re: Parse delimited string in a Stored procedure

Left by Jeppe Andreasen at 1/25/2009 10:21 AM

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

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

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

thank you very much .

# re: Parse delimited string in a Stored procedure

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

thankss

# re: Parse delimited string in a Stored procedure

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

thanks you

# re: Parse delimited string in a Stored procedure

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

thnks

# re: Parse delimited string in a Stored procedure

Left by Chat at 3/13/2009 2:03 AM

thank you ..

# re: Parse delimited string in a Stored procedure

Left by ligtv izle at 3/18/2009 10:36 AM

thank you!

# re: Parse delimited string in a Stored procedure

Left by Mynet at 3/23/2009 4:52 AM

thank you kanka

# Estetik

Left by Estetik at 3/24/2009 3:18 AM

Thanks kral

# re: Parse delimited string in a Stored procedure

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

thanki kanki

# re: Parse delimited string in a Stored procedure

Left by ligtv izle at 4/6/2009 2:22 AM

you are my desire..

# re: Parse delimited string in a Stored procedure

Left by chat at 4/11/2009 10:42 PM

thank you turkish chat34 !

# re: Parse delimited string in a Stored procedure

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

thankx you

# re: Parse delimited string in a Stored procedure

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

thank

# re: Parse delimited string in a Stored procedure

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

turkish justin tv..

# re: Parse delimited string in a Stored procedure

Left by Harsh at 5/7/2009 2:14 AM

Good one..!!

# re: Parse delimited string in a Stored procedure

Left by Sohbet at 5/13/2009 12:24 PM

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

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

thank you admin

# re: Parse delimited string in a Stored procedure

Left by tolga at 7/1/2009 5:12 PM

Thank You Gavur

# re: Parse delimited string in a Stored procedure

Left by sXe at 7/1/2009 5:14 PM

Thank YOu Foorro

# re: Parse delimited string in a Stored procedure

Left by mp3 dinle at 7/10/2009 4:51 PM

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

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

Thank You admin

# re: Parse delimited string in a Stored procedure

Left by wéBurak at 7/10/2009 4:58 PM

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

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

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

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

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

Thanks for the code

# re: Parse delimited string in a Stored procedure

Left by anil at 9/12/2009 1:10 PM

helpfull post thank you

# re: Parse delimited string in a Stored procedure

Left by gaban at 9/12/2009 1:11 PM

Thanks good post

# re: Parse delimited string in a Stored procedure

Left by yaprak at 9/12/2009 1:14 PM

what i need thank you

# re: Parse delimited string in a Stored procedure

Left by sellini at 9/12/2009 1:17 PM

good post thank you

# re: Parse delimited string in a Stored procedure

Left by ozer at 9/12/2009 1:22 PM

thnx good post

# re: Parse delimited string in a Stored procedure

Left by elite at 9/12/2009 1:25 PM

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

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

thank you i really need it

# re: Parse delimited string in a Stored procedure

Left by Domatessuyu at 10/31/2009 12:49 PM

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

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

nice site thanks !!

# re: Parse delimited string in a Stored procedure

Left by Karim Kenawy at 12/21/2009 2:24 AM

Thanks, it worked fine.

# re: Parse delimited string in a Stored procedure

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

Thanks man

worked fine

# re: Parse delimited string in a Stored procedure

Left by Stejan at 1/28/2010 4:41 AM

Thank . Nice post

Your comment:



 (will not be displayed)


 
 
 
Please add 8 and 3 and type the answer here:
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
28123456
78910111213