Loading

.net core dapper SQLServer 从 select where in (...) 到 Table-Valued Parameters

Dapper实现select in的list支持

Dapper默认支持IEnumerable<int>类型的SQL查询语句转换,样例如下:

var lst1 = connection.Query("select * from Table_1 where Id in @Ids", new { Ids = new int[] { 1, 2, 3 } });//等同: where Id in (@Ids1, @Ids2, @Ids3) , @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3

通过select where in语句进行数据库查询,其实是比较常见的,
但是此类查询语句in中能够接收的列表数量是有限的,如SQL Server 2008 R2这个上限是2100。而且in语句查询效率较低。
因此在大批量数据查询时,可采用SQLServer的Table-Valued Parameters特性来处理。

Dapper使用AsTableValuedParameter替代select in

首先需要在数据库中预先创建TVP类型

CREATE TYPE [dbo].[IDListType] AS TABLE([Id] [int] NOT NULL)

在调用时,创建对应的DataTable作为参数

var tvpTable = new DataTable();
tvpTable.Columns.Add(new DataColumn("Id", typeof(int)));
tvpTable.Rows.Add(1);
tvpTable.Rows.Add(2);
tvpTable.Rows.Add(3);

在Dapper调用查询时将in替换为inner join

var sql = "SELECT * FROM Table_1 t1 INNER JOIN @tvp t2 ON t1.Id = t2.Id";
conn.Query(sql, new {tvp = tvpTable.AsTableValuedParameter("dbo.IDListType")});

TVP也适用于小于1000条的数据插入,更新等操作。

样例代码下载:
https://github.com/wswind/dapper-demo.git

参考:
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters
https://medium.com/dapper-net/sql-server-specific-features-2773d894a6ae
https://stackoverflow.com/questions/41132350/is-there-a-way-to-pass-a-tvp-to-dapper-on-net-core-right-now
https://stackoverflow.com/questions/8388093/select-from-x-where-id-in-with-dapper-orm
https://github.com/StackExchange/Dapper
https://docs.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine?view=sql-server-ver15#BulkInsert

posted @ 2020-10-16 10:32  wswind  阅读(494)  评论(0编辑  收藏  举报