SQL Server:将列名指定为属性,将节点值指定为FOR XML

时间:2016-09-22 09:55:15

标签: sql sql-server-2008 tsql for-xml

我需要从SQL Server返回XML格式的列别名。 XML需要如下所示:

<Records>
    <Record>
      <Field FieldName="PURCHASE_DETAIL_ID">31320</Field>
      <Field FieldName="ORDER_ID">6507</Field>
      <Field FieldName="PRODUCT_ORDER">1</Field>
    </Record>   
</Records>

我的表格如下:

PURCHASE_DETAIL_ID  |   ORDER_ID    | PRODUCT_ORDER
----------------------------------------------------
    31320               6507                1

我想使用FOR XML XML提取方法。

我尝试了以下内容,它适用于单列,但不适用于多列。

SELECT  
    'PURCHASE_DETAIL_ID' AS [Field/@FieldName],
    'GOLI' + RTRIM(CONVERT(VARCHAR(10), ol.ID)) AS [Field],
    'ORDER_ID' AS [Field/@FieldName],
    o.ID AS [Field],
    'PRODUCT_ID' AS [Field/@FieldName],
    P.ID AS [Field]
FROM ...
WHERE ...
FOR XML PATH('Record'), ROOT('Records')

2 个答案:

答案 0 :(得分:2)

这就是你要做的......

SELECT  
    'PURCHASE_DETAIL_ID' AS [Field/@FieldName],
    'GOLI' + RTRIM(CONVERT(VARCHAR(10), ol.ID)) AS [Field],
'',
    'ORDER_ID' AS [Field/@FieldName],
    o.ID AS [Field],
'',
    'PRODUCT_ID' AS [Field/@FieldName],
    P.ID AS [Field]
FROM ...
WHERE ...
FOR XML PATH('Record'), ROOT('Records')

答案 1 :(得分:1)

您可以尝试使用xml节点值,如下所示:

declare @xml xml = 
'<Records>
    <Record>
      <Field FieldName="PURCHASE_DETAIL_ID">31320</Field>
      <Field FieldName="ORDER_ID">6507</Field>
      <Field FieldName="PRODUCT_ORDER">1</Field>
    </Record>   
</Records>'

;with cte as (
SELECT T.c.value('@FieldName', 'nvarchar(max)') AS result, T.c.value('.','int') as val  
FROM   @xml.nodes('/Records/Record/Field') T(c) 
)
select * from cte 
pivot (max(val) for result in ([PURCHASE_DETAIL_ID],[ORDER_ID],[PRODUCT_ORDER]) ) p

输出将如下:

enter image description here

如果要以行方式获得结果,可以单独在cte中执行查询

SELECT T.c.value('@FieldName', 'nvarchar(max)') AS result, T.c.value('.','int') as val  
FROM   @xml.nodes('/Records/Record/Field') T(c) 

这将起作用