C# ADO:优化查询及其性能

C# ADO: Optimize query and its performance

我有一个 C# RestApi,它需要通过执行如下查询使用 ADO 从数据库中提取记录信息:

declare @id1 int 
set @id1 =  (select id from myTable where col1= x1, col2 = y1, col3 = z1 from mappingTable)

declare @id2 int 
set @id2 =  (select id from myTable where col1= x2, col2 = y2, col3 = z2 from mappingTable)

declare @id3 int 
set @id3 =  (select id from myTable where col1= x3, col2 = y3, col3 = z3 from mappingTable)
.
.
.
declare @idN int 
set @idN =  (select id from myTable where col1= xN, col2 = yN, col3 = zN from mappingTable)

select @id1,@id2,@id3, ..., @idN

I 运行 query which 运行s N queries inside it using ADO.NET SqlCommand 并读取结果。我有两个问题:

  1. 运行使用单独的 SqlCommand 处理每个查询是否会导致性能下降?通常在 I/O 任务中,执行许多小的 I/O 任务比 运行 在一批 I/O 任务中执行所有任务的性能要低,但我不知道相同的场景数据库和 ADO。
  2. 是否有更好的方法可以使用更好的 SQL 查询来提取相同的结果?换句话说,我可以用其他方式编写此查询以 运行 它具有更好的性能吗?

注意:在上面的查询中,列和表在所有查询中都是相同的,只是修改了 where 子句中的值。

使用 table 值参数存储 xyz 的相应值。 使用单个查询,在其中将 mappingTable 与 table 值参数进行内部连接。

在SQL中:

CREATE TYPE XYZ As Table -- Do not call it XYZ!!!
(
    x int,
    y int,
    z int -- I'm using ints because it's simple - you need the data types of your columns here
)

在c#中,创建一个对应这个类型的数据table:

var dt = new DataTable();
dt.Columns.Add("x", typeof(int));
dt.Columns.Add("y", typeof(int));
dt.Columns.Add("z", typeof(int));

用正确的值填充数据 table,然后将数据 table 作为 SqlDbType.Structured 类型的参数发送到 SQL 服务器:

 cmd.Parameters.Add("@tvp", SqlDbType.Structured).Value = dt;

要在查询中使用它:

SELECT id 
FROM mappingTable
JOIN @tvp
    ON col1= x
   AND col2 = y
   AND col3 = z

这将 return 一个包含单列的记录集,其中包含您需要的所有 ID。

注意:代码直接写在这里 - 可能有一些错别字。