在SQL Server中查询XML字段

时间:2014-08-21 21:51:19

标签: sql sql-server xml tsql sqlxml

我使用的是sql server 2008 R2。我的表X包含具有以下结构的列XML

<rec>
  <set>
    <Raw CLOrderID="GGM-30-08/24/10" Rej="Preopen" Sym="A" Tm="06:36:29.524" />
  </set>
</rec>

我想解析列XML并返回输出如下:

CLOrderID                Rej       Sym        Tm
GGM-30-08/24/10          Preopen   A           06:36:29.524

2 个答案:

答案 0 :(得分:0)

这可以通过一些用于xml调用来完成。如果存在/ rec / set / Raw / @ *,则此结构对于将来的架构更改也保持灵活性。如果更改,您始终可以添加一个管道,其中包含您要抓取的属性的新路径。希望这会有所帮助。

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

答案 1 :(得分:0)

使用nodes()粉碎XML,value()提取属性值。

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)

如果您确定只为每个XML提取了一行,则可以直接获取属性值而不先进行分解。

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