简体   繁体   中英

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"

Use nodes() method to split your rows and then get values: Check this solution and hope it helps you:

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.

Note : Event column in your table must be XML datatype.

To get the data into specific fields you could extract them directly from the 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"
[1] : use the first one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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