这里使用表值参数是一个不错的选择。对于初学者,您可以在 SQL Server 中使用create a custom table type,如下所示:
create type dbo.IdentifierList as table (Identifier int not null);
这是一个简单的 C# 函数,用于创建具有这种类型的查询参数的实例:
SqlParameter CreateIdentifierTableParameter(string name, IEnumerable<int> identifiers)
{
// Build a DataTable whose schema matches that of our custom table type.
var identifierTable = new DataTable(name);
identifierTable.Columns.Add("Identifier", typeof(long));
foreach (var identifier in identifiers)
identifierTable.Rows.Add(identifier);
return new SqlParameter
{
ParameterName = name, // The name of the parameter in the query to be run.
TypeName = "dbo.IdentifierList", // The name of our table type.
SqlDbType = SqlDbType.Structured, // Indicates a table-valued parameter.
Value = identifierTable, // The table created above.
};
}
然后您使用@RoomIds 参数编写查询,将其视为数据库中的任何其他表,调用上面创建的函数来构建表值参数,然后像您一样将其添加到您的 SQL 命令中任何其他SqlParameter。例如:
void GetMeetings(IEnumerable<int> roomIdentifiers)
{
// A simplified version of your query to show just the relevant part:
const string sqlText = @"
select
M.*
from
Meeting M
where
exists (select 1 from @RoomIds R where M.RoomId = R.Identifier);";
using (var sqlCon = new SqlConnection("<your connection string here>"))
{
sqlCon.Open();
using (var sqlCmd = new SqlCommand(sqlText, sqlCon))
{
sqlCmd.Parameters.Add(CreateIdentifierTableParameter("RoomIds", roomIdentifiers));
// Execute sqlCmd here in whatever way is appropriate.
}
}
}
一开始这似乎需要做很多工作,但是一旦您定义了 SQL 类型并编写了一些代码来创建它的实例,就很容易在需要的地方重用它。