【发布时间】:2015-10-06 15:59:16
【问题描述】:
我正在尝试使用 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')
不过,这个表中将有大约 70 列。现在我会暴力破解它,但如果有人知道更好的方法,请告诉我。干杯
【问题讨论】:
标签: sql xml sql-server-2008