将行转换为sql server中的列

时间:2017-05-16 11:59:55

标签: sql sql-server tsql sql-server-2014-express

解析XML

后,我得到如下输出
Name        Type        Value 
doccreated  datetime    2017-05-05
docmodified datetime    2017-05-06
version     varchar(10) 3.1.42  
doccreated  datetime    2017-04-11
docmodified datetime    2017-04-12
version     varchar(10) 3.1.43  

我需要输出如下。

doccreated  docmodified version
2017-05-05  2017-05-06  3.1.42  
2017-04-11  2017-04-12  3.1.43

1 个答案:

答案 0 :(得分:0)

:此

DECLARE @yourXML XML =
'<root> <records> <record> <field name="doccreated" type="DateTime">2002-09-28T18:17:32.12Z</field> <field name="docmodified" type="DateTime">2002-11-19T15:18:26.19Z</field> <field name="Version" type="Double">3.1.43</field> </record> <record> <field name="doccreated" type="DateTime">2002-09-28T18:17:32.09Z</field> <field name="docmodified" type="DateTime">2002-12-13T15:53:50.66Z</field> <field name="Version" type="Double">3.1.43</field></record> </records> </root>'

SELECT 
  doccreated  = x.record.value('(field[@name="doccreated"]/text())[1]', 'date'),
  docmodified = x.record.value('(field[@name="docmodified"]/text())[1]', 'date'),
  [version]   = x.record.value('(field[@name="Version"]/text())[1]', 'varchar(10)')
FROM @yourXML.nodes('/root/records/record') x(record);

<强>结果

doccreated docmodified version
---------- ----------- ----------
2002-09-28 2002-11-19  3.1.43
2002-09-28 2002-12-13  3.1.43