如何构造一个允许我传递(例如)的存储过程,@IDList
以便我可以编写:
Select * from Foo Where ID in @IDList
这可行吗?
使用SQL2005及更高版本,您可以直接从代码发送数组.
首先创建一个自定义类型
CREATE TYPE Array AS table (Item varchar(MAX))
比存储过程.
CREATE PROCEDURE sp_TakeArray @array AS Array READONLY AS BEGIN Select * from Foo Where ID in (SELECT Item FROM @array) END
然后从传递DataTable的代码作为数组调用
DataTable items = new DataTable(); items.Columns.Add( "Item", typeof( string ) ); DataRow row = items.NewRow(); row.SetField( "Item", - ); 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();