试图从SQL Server获取XML字段

时间:2017-06-12 23:43:19

标签: sql sql-server xml

我从表中获取数据,其中一列是XML格式的。该列称为“已更新”,该表为“审核”。字段看起来像这样:

    <Fields><Field Name="DateFrom"/><Field Name = "Type 1"/><Field Name = "Type 2/></Fields>

    <Fields><Field Name = "DateFrom"/></Fields>

    <Fields><Field Name="DateFrom"/><Field Name = "Note"/><Field Name = "Type 1"/></Fields>

XML字段是更大查询的一部分:

    Select id, Updated
    from Audit

结尾将如下所示,ID为非XML列。

ID     Updated

123    DateFrom, Type1, Type2
323    DateFrom
455    DateFrom, Note, Type1

我尝试了一些我在网上找到的东西,但我没有正确地做到这一点。我试过的一种方法是:

    Select Updated.value('/Fields/Field Name)[1]', 'nvarchar(max)') as NewUpdated from Audit.

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以像这样使用valuenodesstuff

   DECLARE @Audit AS TABLE
(
   Id int,
   Updated xml
)

INSERT INTO @Audit
(
   Id,
   Updated
)
VALUES
(1,N'<Fields><Field Name="DateFrom"/><Field Name = "Type 1"/><Field Name = "Type 2" /></Fields>'),
(2,N'<Fields><Field Name = "DateFrom"/></Fields>'),
(3, N'<Fields><Field Name="DateFrom"/><Field Name = "Note"/><Field Name = "Type 1"/></Fields>')    

  SELECT a.Id, ca.NewUpdated
 FROM @Audit a
   CROSS APPLY
   (
     SELECT  STUFF(
                   (SELECT ', ' + x.n.value('(./@Name)[1]', 'varchar(20)') 
                   FROM a.Updated.nodes('/Fields/Field') x(n)
                   FOR XML PATH('') 
                ),1,2,'')   AS NewUpdated  
   ) ca

演示链接:http://rextester.com/NNF94534