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

时间:2016-11-28 05:40:32

标签: sql sql-server

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”获取数据

2 个答案:

答案 0 :(得分:2)

使用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数据类型。

答案 1 :(得分:0)

要将数据导入特定字段,您可以直接从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”]:只获取门户网站=“FB”的玩家标签 [1]:使用第一个