Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an "in" list via stored procedure [duplicate]

How can I construct a stored procedure that will allow me to pass (for example) an @IDList so that I can write:

Select * from Foo Where ID in @IDList

Is this doable?

like image 819
klkitchens Avatar asked Mar 06 '09 04:03

klkitchens


1 Answers

With SQL2005 and above you can send an array from code directly.

First create a custom type

CREATE TYPE Array AS table (Item varchar(MAX))

Than the stored procedure.

CREATE PROCEDURE sp_TakeArray
    @array AS Array READONLY
AS BEGIN
    Select * from Foo Where ID in (SELECT Item FROM @array)
END

Then call from code passing in a DataTable as the array

DataTable items = new DataTable();
items.Columns.Add( "Item", typeof( string ) );

DataRow row = items.NewRow();
row.SetField<string>( "Item", <item to add> );
items.Rows.Add( row );

SqlCommand command = new SqlCommand( "sp_TakeArray", connection );
command.CommandType = CommandType.StoredProcedure;
SqlParameter param = command.Parameters.Add( "@Array", SqlDbType.Structured );
param.Value = items;
param.TypeName = "dbo.Array";

SqlDataReader reader = command.ExecuteReader();
like image 91
bstoney Avatar answered Oct 29 '22 21:10

bstoney