Better than dynamic SQL - How to pass a list of comma separated IDs into a stored proc

Posted by Rodney Vinyard on Geeks with Blogs See other posts from Geeks with Blogs or by Rodney Vinyard
Published on Fri, 28 May 2010 18:56:12 GMT Indexed on 2010/05/28 19:02 UTC
Read the original article Hit count: 331

Filed under:

Better than dynamic SQL - How to pass a list of comma separated IDs into a stored proc:

 

 

Derived form "Method 6" from a great article:

·         How to pass a list of values or array to SQL Server stored procedure

·          http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm

 

 

Create PROCEDURE [dbo].[GetMyTable_ListByCommaSepReqIds]

(@CommaSepReqIds varchar(500))

 

AS

 

BEGIN

 

select * from MyTable q

              JOIN

              dbo.SplitStringToNumberTable(@CommaSepReqIds) AS s

              ON

              q.MyTableId = s.ID

End

 

 

ALTER FUNCTION [dbo].[SplitStringToNumberTable]

(

       @commaSeparatedList varchar(500)

)

RETURNS

@outTable table

(

       ID int

)

AS

BEGIN

       DECLARE @parsedItem varchar(10), @Pos int

 

       SET @commaSeparatedList = LTRIM(RTRIM(@commaSeparatedList))+ ','

       SET @commaSeparatedList = REPLACE(@commaSeparatedList, ' ', '')

       SET @Pos = CHARINDEX(',', @commaSeparatedList, 1)

 

       IF REPLACE(@commaSeparatedList, ',', '') <> ''

       BEGIN

              WHILE @Pos > 0

              BEGIN

                     SET @parsedItem = LTRIM(RTRIM(LEFT(@commaSeparatedList, @Pos - 1)))

                     IF @parsedItem <> ''

                           BEGIN

                                  INSERT INTO @outTable (ID)

                                  VALUES (CAST(@parsedItem AS int)) --Use Appropriate conversion

                           END

                           SET @commaSeparatedList = RIGHT(@commaSeparatedList, LEN(@commaSeparatedList) - @Pos)

                           SET @Pos = CHARINDEX(',', @commaSeparatedList, 1)

              END

       END   

       RETURN

END

 

 

 

 

 

© Geeks with Blogs or respective owner