将SQL输出到XML时,格式有问题。
以下按预期方式工作: -
SELECT
AC.ACCOUNT AS 'Acct',
(SELECT ITEMNO AS 'ITEM'
FROM ITEMS AS ITEMS1 WITH(NOEXPAND)
WHERE ITEMS1.CODE = AC.CODE
FOR XML PATH ('Items'), TYPE)
FROM
AC WITH(NOLOCK)
INNER JOIN
ITEMS ON AC.CODE = ITEMS.CODE
FOR XML PATH (''), ROOT ('Accts'), ELEMENTS
哪个输出以下XML:
<Accts>
<Acct>94615130</Acct>
<Items>
<ITEM>1001</ITEM>
</Items>
<Items>
<ITEM>1050</ITEM>
</Items>
<Items>
<ITEM>1051</ITEM>
</Items>
<Items>
<ITEM>1054</ITEM>
</Items>
<Items>
<ITEM>1055</ITEM>
</Items>
....
</Accts>
但是当我在子查询的位置添加一个额外的子句时:
SELECT
AC.ACCOUNT AS 'Acct',
(SELECT ITEMNO AS 'ITEM'
FROM ITEMS AS ITEMS1 WITH(NOEXPAND)
WHERE ITEMS1.CODE = AC.CODE
AND ITEMS1.ITEMNO = ITEMS.ITEMNO
FOR XML PATH ('Items'), TYPE)
FROM
AC WITH(NOLOCK)
INNER JOIN
ITEMS ON AC.CODE = ITEMS.CODE
FOR XML PATH (''), ROOT ('Accts'), ELEMENTS
我得到这个xml输出:
<Accts>
<Acct>94615130</Acct>
<Items>
<ITEM>28</ITEM>
</Items>
<Acct>94615130</Acct>
<Items>
<ITEM>36</ITEM>
</Items>
<Acct>94615130</Acct>
<Items>
<ITEM>114</ITEM>
</Items>
<Acct>94615130</Acct>
<Items>
<ITEM>161</ITEM>
</Items>
....
</Accts>
这不是我想要的。我需要在第一个示例中将所有项目分组到帐号下,而不是重复每个项目的帐号。
我正在使用Microsoft SQL Server 2008,欢迎任何帮助。
答案 0 :(得分:0)
我认为您需要摆脱外部查询中的内部联接。即:
SELECT
AC.ACCOUNT AS 'Acct',
(SELECT ITEMNO AS 'ITEM'
FROM ITEMS AS ITEMS1
WHERE ITEMS1.CODE = AC.CODE
FOR XML PATH ('Items'), TYPE)
FROM
AC
FOR XML PATH (''), ROOT ('Accts'), ELEMENTS