我正在尝试通过SQL查询生成XML文件,并且我有一个包含以下列的表:
ItemNumber, Price, DateFrom, DateTo
我用来生成XML的代码是:
SELECT
ItemNumber AS '@ItemNumber',
Price AS '@Price',
DateFrom AS 'DateFrom',
DateTo AS 'DateTo'
FROM
#tempXML
FOR XML PATH('Item')
我期望得到的是这样的:
<Item id="111">
<ItemNumber>111</ItemNumber>
<Price value="3000">
<DateFrom>2018-01-02</DateFrom>
<DateTo>2018-01-30</DateTo>
</Price>
<Price value="2500">
<DateFrom>2018-01-31</DateFrom>
<DateTo>2018-11-22</DateTo>
</Price>
</Item>
<Item>
<ItemNumber>120</ItemNumber>
<Price value="4000">
<DateFrom>2018-01-12</DateFrom>
<DateTo>2018-11-22</DateTo>
</Price>
</Item>
但是我却得到了更多类似的东西:
<Item
ItemNumber="111"
Price="3000">
<DateFrom>2018-01-02</DateFrom>
<DateTo>2018-01-30</DateTo>
</Item>
<Item
ItemNumber="111"
Price="2500">
<DateFrom>2018-01-31</DateFrom>
<DateTo>2018-11-22</DateTo>
</Item>
<Item
ItemNumber="120"
Price="4000">
<DateFrom>2018-01-12</DateFrom>
<DateTo>2018-11-22</DateTo>
</Item>
任何帮助将不胜感激
Sample data from the table I use
CREATE TABLE #tempXML
(
ItemNumber INT,
Price INT,
DateFrom DATE,
DateTo DATE
)
INSERT INTO #tempXML
VALUES
(111, 3000, '2018-01-02', '2018-01-30'),
(111, 2500, '2018-01-31', '2018-11-22'),
(120, 4000, '2018-01-12', '2018-11-22')
答案 0 :(得分:1)
您可以这样指定元素的嵌套方式:
SELECT
ItemNumber AS '@id',
ItemNumber AS 'ItemNumber',
Price AS 'Price/@value',
DateFrom AS 'Price/DateFrom',
DateTo AS 'Price/DateTo'
FROM
#tempXML
FOR XML PATH('Item');
答案 1 :(得分:1)
这似乎是您所追求的,但是有点混乱:
SELECT T.ItemNumber AS [@ID],
(SELECT T.ItemNumber,
(SELECT sq.Price AS [@value],
(SELECT sq.DateFrom,
sq.DateTo
FOR XML PATH(''),TYPE)
FROM #tempXML sq
WHERE sq.ItemNumber = T.ItemNumber
FOR XML PATH('Price'),TYPE)
FOR XML PATH(''),TYPE)
FROM #tempXML T
GROUP BY ItemNumber
FOR XML PATH ('Item');
结果是:
<Item ID="111">
<ItemNumber>111</ItemNumber>
<Price value="3000">
<DateFrom>2018-01-02</DateFrom>
<DateTo>2018-01-30</DateTo>
</Price>
<Price value="2500">
<DateFrom>2018-01-31</DateFrom>
<DateTo>2018-11-22</DateTo>
</Price>
</Item>
<Item ID="120">
<ItemNumber>120</ItemNumber>
<Price value="4000">
<DateFrom>2018-01-12</DateFrom>
<DateTo>2018-11-22</DateTo>
</Price>
</Item>
答案 2 :(得分:0)
还有一个建议,简单一点...
SELECT t1.ItemNumber AS [@id]
,t1.ItemNumber
,(
SELECT t2.Price AS [@value]
,t2.DateFrom
,t2.DateTo
FROM #tempXML t2
WHERE t1.ItemNumber=t2.ItemNumber
FOR XML PATH('Price'),TYPE
)
FROM #tempXML t1
GROUP BY t1.ItemNumber
FOR XML PATH('Item');
一些说明:
GROUP BY
会将外部SELECT
减少为 one-row-per-ItemNumber ,而 sub-select 将充当相关子查询,并获取给定商品的所有价格明细。