2016-09-22 65 views
0

我需要從SQL Server返回XML中包含空格的列別名。 XML需要是這樣的:SQL Server:將列名稱指定爲屬性,並將節點值指定爲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 

我想使用XML提取FOR 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') 

回答

1

這是你必須做的事情......

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') 
+0

」是你在這裏的新東西...... –

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) 

這將工作

+0

我想要做反向 –

+0

反向意味着你可以執行CTE內的查詢將工作SELECT Tcvalue(」 (c) –

+0

已答覆更新回答(0)分享到:0 0條評論,0人蔘與。我有話說...使用社交帳號登錄發佈前先點擊左邊的按鈕登錄最新評論最新評論√最早評論最熱評論還沒有評論友言?根據您的評論 –

相關問題