在SQL中将单个XML值分隔为多个行

时间:2014-12-24 06:01:43

标签: sql sql-server xml tsql

我有以下格式的表格,

MENUACTION         VALUE

ReceivedDetails    <KEY /><ACCOUNTNO v="3275402GBP" /><AGR1 /><AGR2 /><PAY1 /><PAY2>

我需要以下格式的表格

MENUACTION         VALUE

ReceivedDetails    ACCOUNTNO v="3275402GBP"
ReceivedDetails    AGR1
ReceivedDetails    AGR2
ReceivedDetails    PAY2

注意: 值列中的记录是动态的,我们需要在KEY标记

之后分隔标记

你能帮忙吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

create table #tmp (MENUACTION NVARCHAR(100), VALUE NVARCHAR(100))
insert into #tmp (MENUACTION, VALUE) values (('ReceivedDetails'), ('<KEY /><ACCOUNTNO v="3275402GBP" /><AGR1 /><AGR2 /><PAY1 /><PAY2 />'));

with src as 
(
    select MENUACTION, cast(VALUE as XML) [xml]
    from #tmp
)
select src.MENUACTION
, cast(x.y.query('.') as nvarchar(100)) [VALUE_XML]
, x.y.value('local-name(.)', 'nvarchar(100)') [VALUE_STR]
, x.y.value('@v', 'nvarchar(100)') [v_attribute]
from src
cross apply src.[xml].nodes('/*') as x(y)


drop table #tmp

结果:

MENUACTION      VALUE_XML                   VALUE_STR   v_attribute
-------------------------------------------------------------------
ReceivedDetails <KEY/>                      KEY         NULL
ReceivedDetails <ACCOUNTNO v="3275402GBP"/> ACCOUNTNO   3275402GBP
ReceivedDetails <AGR1/>                     AGR1        NULL
ReceivedDetails <AGR2/>                     AGR2        NULL
ReceivedDetails <PAY1/>                     PAY1        NULL
ReceivedDetails <PAY2/>                     PAY2        NULL

检查SQLFiddle