加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用 XML 查询替换 ADO.NET 中的 IN ,提高查询性能

发布时间:2020-12-15 22:54:23 所属栏目:百科 来源:网络整理
导读:为了解决在大数据查询时不使用 in 操作符,所以使用下面的方案替换 in 的使用 -------------------------------------------------- --1.优化前后代码对比 优化前的代码: select * from orderinfo where orderid in (1,2,3,4,5,........,n); 优化后的代码:

为了解决在大数据查询时不使用 in 操作符,所以使用下面的方案替换 in 的使用

--------------------------------------------------

--1.优化前后代码对比

优化前的代码:

select * from orderinfo where orderid in (1,2,3,4,5,........,n);

优化后的代码:

declare @xmlDoc xml;
set @xmlDoc='
<orders title="订单号">
<id>1111</id>
<id>2222</id>
<id>3333</id>
<id>4444</id>
</orders>';
select * from orderinfo
where exists
(
select 1 from @xmlDoc.nodes('/orders/id') as T(c)
where T.c.value('text()[1]','int')= orderinfo.OrderID
);

--------------------------------------------------

--2.其它基础的 xquery 使用

declare @xmlDoc xml; set @xmlDoc=' <orders title="订单号"> <id>862875</id> <id>862874</id> <id>862873</id> <id>862872</id> </orders>'; --查询所有Id节点 select @xmlDoc.query('/orders/id') c1 --查询第一个Id节点值,@xmlDoc.value('(/orders/id)[1]','nvarchar(max)') AS c2 --查询最后一个Id节点值,@xmlDoc.value('(/orders/id)[last()]','nvarchar(max)') AS c3 --查找属性,@xmlDoc.value('(/orders/@title)[1]','nvarchar(max)') AS c4 --xml 与表合并查询1(推荐) select * from orderinfo where exists ( select 1 from @xmlDoc.nodes('/orders/id') as T(c) where T.c.value('text()[1]','int')= orderinfo.OrderID ); --xml 与表合并查询(和in效果一样) select * from orderinfo where OrderID in ( select T.c.value('text()[1]','int') from @xmlDoc.nodes('/orders/id') as T(c) ); ---------------------------------- --3. ADO.NET 中执行xml查询 DataTable dt = new DataTable(); using (SqlConnection conn = new SqlConnection(connectionString)) { string xml = @" <orders title="订单号"> <id>862875</id> <id>862874</id> <id>862873</id> <id>862872</id> </orders> "; SqlCommand comm = conn.CreateCommand(); comm.CommandText = @" select * from orderinfo where exists ( select 1 from @xmlDoc.nodes('/orders/id') as T(c) where T.c.value('text()[1]','int')= orderinfo.OrderID );"; comm.Parameters.Add(new SqlParameter("@xml",SqlDbType.Xml) { Value = xml }); using (SqlDataAdapter adapter = new SqlDataAdapter(comm)) { adapter.SelectCommand = comm; adapter.Fill(dt); } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读