需要有关SQL XML Query的帮助

时间:2011-02-22 16:21:41

标签: sql-server xml

我几乎没有使用T-SQL查询XML数据的经验。鉴于下面显示的XML,我将如何提取“Sub_ID”值?

<MESSAGE LABEL = "IVSWEEP" >
    <H 
        SIMULATOR = "54355" 
        COMMENT = "" 
        OPERATOR = "Operator" 
        SUB_ID = "090617041199" 
        PROCESS_CD = "AHIPOT" 
        DATE_TIME = "6/19/2009 11:57:35 AM" 
        TMOD = "23.05" 
        TCOR = "23.05" 
        <D P = "0" I = "0" V = "0" />
        <D P = "1" I = "1.250854" V = "0" />
        <D P = "2" I = "1.251904" V = "4.212341" />
        <D P = "3" I = "1.24895" V = "7.517395" />
    </H>
</MESSAGE>

1 个答案:

答案 0 :(得分:1)

这是一种方法。您的XML无效。缺少>以终止<H

declare @xml xml = '<MESSAGE LABEL = "IVSWEEP" >
    <H 
        SIMULATOR = "54355" 
        COMMENT = "" 
        OPERATOR = "Operator" 
        SUB_ID = "090617041199" 
        PROCESS_CD = "AHIPOT" 
        DATE_TIME = "6/19/2009 11:57:35 AM" 
        TMOD = "23.05" 
        TCOR = "23.05"> 
        <D P = "0" I = "0" V = "0" />
        <D P = "1" I = "1.250854" V = "0" />
        <D P = "2" I = "1.251904" V = "4.212341" />
        <D P = "3" I = "1.24895" V = "7.517395" />
    </H>
</MESSAGE>'

declare @T table (Col1 xml)
insert into @T values(@xml)
insert into @T values(@xml)
insert into @T values(@xml)

select 
  m.h.value('@SUB_ID', 'varchar(50)')
from @T
  cross apply Col1.nodes('MESSAGE/H') as m(h)