使用表值参数(TVP)代替'其中'

时间:2014-10-20 14:57:04

标签: c# dapper

代码this

connection.Execute("delete from Table where ID in @ids", new { ids=listOfIds });
listOfIds太长时

失败。您将获得以下内容:

The incoming request has too many parameters. The server supports a maximum of 2100

(取决于您的rdbms)

理想情况下,我想使用表值参数。我还没有找到一个体面的小巧的例子。有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

这应该有所帮助:

// 1. declare the custom data type
// this is just to make it re-runnable; normally you only do this once
try { connection.Execute("drop type MyIdList"); } catch { }
connection.Execute("create type MyIdList as table(id int);");

// 2. prepare the data; if this isn't a sproc, also set the type name
DataTable ids = new DataTable {
    Columns = {{"id", typeof(int)}},
    Rows = {{1},{3},{5}}
};
ids.SetTypeName("MyIdList");

// 3. run the query, referencing the TVP (note @tmp represents the db data)
int sum = connection.Query<int>(@"
-- spoof some data
declare @tmp table(id int not null);
insert @tmp (id) values(1), (2), (3), (4), (5), (6), (7);
-- the actual query
select * from @tmp t inner join @ids i on i.id = t.id", new { ids }).Sum();
sum.IsEqualTo(9); // just checks the result