繁体   English   中英

如何在SQL Server的XML列上编写查询

[英]How can I write a query in SQL Server on XML column

table tbl_event_log

columnName DataType
id          Int
event       XML
userinfo    XML

数据应该是

<Event><Player readName="9.Make You Talk!" demoName="Video Game" **portal="FB"** totalDuration="0:07/0:07(100%)" /></Event>

我想编写查询以从portal =“ FB”获取数据

使用nodes()方法拆分行然后获取值:检查此解决方案,希望对您有所帮助:

Declare @mytable table (id int,event xml,userinfo varchar(200))

Insert into @mytable
select 1, '<Event><Player readName="9.Make You Talk!" demoName="Video Game" portal="FB" totalDuration="0:07/0:07(100%)" /></Event>','Test'
Union
select 2, '<Event><Player readName="9.Make You Talk!" demoName="Video Game" portal="TW" totalDuration="0:07/0:07(100%)" /></Event>','Test'



select
    s.id,
    e.p.value('@portal', 'varchar(max)') as portal
from @mytable as s
    outer apply s.event.nodes('Event/Player') as e(p)

select * from (
select
    s.id,
    e.p.value('@portal', 'varchar(max)') as portal
from @mytable as s
    outer apply s.event.nodes('Event/Player') as e(p)
) Test
where Test.portal = 'FB'

Attn:将@mytable替换为您的表名。

注意 :表中的事件列必须为XML数据类型。

要将数据放入特定字段,您可以直接从xml中提取它们。

例如:

select id, userinfo,
event.value('/Event[1]/Player[@portal="FB"][1]/@readName','varchar(max)') as readNameFB,
event.value('/Event[1]/Player[@portal="FB"][1]/@demoName','varchar(max)') as demoNameFB,
event.value('/Event[1]/Player[@portal="FB"][1]/@totalDuration','varchar(30)') as totalDurationFB
from tbl_event_log;

[@ portal =“ FB”]:仅在portal =“ FB”的位置获得Player标签
[1]:使用第一个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM