[英]How can I write a query in SQL Server on XML column
table tbl_event_log
columnName DataType
id Int
event XML
userinfo XML
and data should be in event is 数据应该是
<Event><Player readName="9.Make You Talk!" demoName="Video Game" **portal="FB"** totalDuration="0:07/0:07(100%)" /></Event>
and i want to write query to get data from portal="FB" 我想编写查询以从portal =“ FB”获取数据
Use nodes()
method to split your rows and then get values: Check this solution and hope it helps you: 使用
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: Replace @mytable with your table name. Attn:将@mytable替换为您的表名。
Note : Event column in your table must be XML datatype. 注意 :表中的事件列必须为XML数据类型。
To get the data into specific fields you could extract them directly from the xml. 要将数据放入特定字段,您可以直接从xml中提取它们。
For example: 例如:
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"] : only get the Player tags where the portal="FB" [@ portal =“ FB”]:仅在portal =“ FB”的位置获得Player标签
[1] : use the first one [1]:使用第一个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.