I am using sql server 2008 R2. I have table X with Column XXML with the following structure
<rec>
<set>
<Raw CLOrderID="GGM-30-08/24/10" Rej="Preopen" Sym="A" Tm="06:36:29.524" />
</set>
</rec>
I want to parse above column XXML and return output as below:
CLOrderID Rej Sym Tm
GGM-30-08/24/10 Preopen A 06:36:29.524
This can be done with a few for xml calls. This structure also remains flexible for future schema changes, provided /rec/set/Raw/@* is present. If that changes, you can always add a pipe with the new path for the attributes you're wanting to grab. Hope this helps.
declare @x table (id int identity(1,1) primary key, x xml)
insert into @x (x) values ('<rec>
<set>
<Raw CLOrderID="GGM-30-08/24/10" Rej="Preopen" Sym="A" Tm="06:36:29.524" />
</set>
</rec>')
select a.id, cast((
select (
select x.attribs.value('local-name(.)','nvarchar(20)') + ' '
from @x t
outer apply t.x.nodes('/rec/set/Raw/@*') x(attribs)
where t.id = a.id
for xml path('')
), (
select x.attribs.value('.','nvarchar(20)') + ' '
from @x t
outer apply t.x.nodes('/rec/set/Raw/@*') x(attribs)
where t.id = a.id
for xml path('')
)
for xml path('')
) as varchar(500))
from @x a
Use nodes()
to shred the XML and value()
to extract the attribute values.
select T.X.value('@CLOrderID', 'nvarchar(100)') as CLOrderID,
T.X.value('@Rej', 'nvarchar(100)') as Rej,
T.X.value('@Sym', 'nvarchar(100)') as Sym,
T.X.value('@Tm', 'time(3)') as Tm
from dbo.X
cross apply X.XXML.nodes('/rec/set/Raw') as T(X)
If you know for sure that you only will have one row extracted for each XML you can get the attribute values directly without shredding first.
select X.XXML.value('(/rec/set/Raw/@CLOrderID)[1]', 'nvarchar(100)') as CLOrderID,
X.XXML.value('(/rec/set/Raw/@Rej)[1]', 'nvarchar(100)') as Rej,
X.XXML.value('(/rec/set/Raw/@Sym)[1]', 'nvarchar(100)') as Sym,
X.XXML.value('(/rec/set/Raw/@Tm)[1]', 'time(3)') as Tm
from dbo.X
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.