0
我試圖使用SQL生成的XML格式:使用SQL生成XML
<ImportSession>
<Batches>
<Batch>
<BatchFields>
<BatchField Name="Field1" Value="1" />
<BatchField Name="Field2" Value="2" />
<BatchField Name="Field3" Value="3" />
</BatchFields>
<Batch>
<Batches>
</ImportSession>
我使用SQL Server 2008中我寫此查詢:
SELECT
(SELECT
(SELECT
'Col' AS [@Name],
FiscalYear AS [@Value]
FROM [ICEM].[dbo].[ExportedBill]
WHERE ExportedBillID = 1
FOR XML PATH ('BatchField'), TYPE)
FROM [ICEM].[dbo].[ExportedBill]
WHERE ExportedBillID = 1
FOR XML PATH ('BatchFields'), ROOT ('Batch'), TYPE)
FROM
[ICEM].[dbo].[ExportedBill]
WHERE
ExportedBillID = 1
FOR XML PATH ('Batches'), ROOT ('ImportSession')
而且這個結果是:
<ImportSession>
<Batches>
<Batch>
<BatchFields>
<BatchField Name="Col" Value="2015" />
</BatchFields>
</Batch>
</Batches>
</ImportSession>
我需要的是每個列都應該在BatchField中有一個條目。此外,我需要列名顯示在名稱中。所以,我應該得到:
<BatchField Name="FiscalYear" Value="2015" />
<BatchField Name="MeterNumber" Value="123456" />
<BatchField Name="Name" Value="John Smith" />
<BatchField Name="Utility" Value="Electricity" />
因此,誰能告訴我如何修改我的查詢來獲取我需要什麼?
編輯:
我想通了。我需要第二個嵌套的選擇。我需要每列一個。如果他們選擇繼續使用相同的標籤,以前的選擇,則信息是相同的父標籤
SELECT
(SELECT
(SELECT
'FiscalYear' AS [@Name],
FiscalYear AS [@Value]
FROM [ICEM].[dbo].[ExportedBill]
WHERE ExportedBillID = 1
FOR XML PATH ('BatchField'), TYPE),
(SELECT 'FiscalPeriod' AS [@Name],
FiscalPeriod AS [@Value]
FROM [PEEL_ICEM].[dbo].[ExportedBill]
WHERE ExportedBillID = 1
FOR XML PATH ('BatchField'), TYPE)
FROM [ICEM].[dbo].[ExportedBill]
WHERE ExportedBillID = 1
FOR XML PATH ('BatchFields'), ROOT ('Batch'), TYPE)
FROM
[ICEM].[dbo].[ExportedBill]
WHERE
ExportedBillID = 1
FOR XML PATH ('Batches'), ROOT ('ImportSession')
事情是,雖然下concatanated,會出現在該表中的70列。虐待現在,但如果有人知道更好的方式來做到這一點,請讓我知道。歡呼聲
乾杯的人。這有很大幫助。如果我按照自己的方式完成了這個任務,我不會期待這個狀態,因爲我的查詢會處在這個狀態。 – discodowney