You are not Logged in
Would you like to Login or Register

Today is: 05 February 2012
Check this months hot topics

Passing CSV to Stored Procedure

There are many occasions when it would be easier to pass an array of values to a Stored Procedure instead of looping.

This can be done and is very simple to use once implemented, all it needs is a new UDF (User Defined Function).

CREATE FUNCTION dbo.CSVToList (@CSV varchar(3000)) 
    RETURNS @Result TABLE (Value varchar(30))
AS   
BEGIN
    DECLARE @List TABLE
    (
        Value varchar(30)
    )

    DECLARE
        @Value varchar(30),
        @Pos int

    SET @CSV = LTRIM(RTRIM(@CSV))+ ','
    SET @Pos = CHARINDEX(',', @CSV, 1)

    IF REPLACE(@CSV, ',''') <> ''
    BEGIN
        WHILE @Pos > 0
        BEGIN
            SET @Value = LTRIM(RTRIM(LEFT(@CSV, @Pos - 1)))

            IF @Value <> ''
                INSERT INTO @List (Value) VALUES (@Value) 

            SET @CSV = RIGHT(@CSV, LEN(@CSV) - @Pos)
            SET @Pos = CHARINDEX(',', @CSV, 1)
        END
    END     

    INSERT @Result
    SELECT
        Value
    FROM
        @List
    
    RETURN
END

Then to use this you only need to do the following:

DECLARE @CSV varchar(100)
SET @CSV = '30,32,34,36,40'

SELECT 
    ProductID, 
    ProductName, 
    UnitPrice
FROM 
    Products
WHERE
    ProductID IN (SELECT * FROM dbo.CSVToLIst(@CSV))
kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Greg Duffield Skype
Author : Greg Duffield
Published : 14 July 2006

Greg has too many years experience in developement from VB for DOS all the way through to Windows Workflow and LINQ while covering pretty much every technology in between. A complete MS evangelist he is now Director of the only MS Gold Partner IT services company in Norfolk. Wehere they are producing Web 2 Applications for various sectors, and are currently entering the Haulage industry with their latest product.

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views

More Publications

Select Column Information using SQL Server
Dave Howard - 18/09/2006
Full Text Search in SQL 2005
Ric Hayman MCPD - 03/08/2006
Enabling Service Broker
Paul Hayman - 01/08/2006
GRANT Permissions on all of your Stored Procedures using a query
Paul Marshall - 16/06/2006
T-SQL script automatically adds auditing to a table
Dave Howard - 18/09/2006