我有以下表格和内容:
CREATE TABLE [dbo].[MyTable](
[PID] [int] NOT NULL,
[CID] [int] NOT NULL
)
INSERT INTO MyTable values (17344,17345)
INSERT INTO MyTable values (17344,17346)
INSERT INTO MyTable values (17272,17273)
INSERT INTO MyTable values (17272,17255)
INSERT INTO MyTable values (17272,17260)
INSERT INTO MyTable values (17272,17274)
INSERT INTO MyTable values (17272,17252)
由此我需要创建以下XML布局:
<Item code="17344">
<BOMs>
<BOM code="17344">
<BOMLine type="17345"/>
<BOMLine type="17346"/>
</BOM>
</BOMs>
</Item>
<Item code="17272">
<BOMs>
<BOM code="17272">
<BOMLine type="17273"/>
<BOMLine type="17255"/>
<BOMLine type="17260"/>
<BOMLine type="17274"/>
<BOMLine type="17252"/>
</BOM>
</BOMs>
</Item>
我正试图通过以下语句来实现这一点,这句话给了我太多的行和重复:
DECLARE @test XML
SELECT @test =
(SELECT PID '@code',
(SELECT PID as '@code',
(SELECT CID as '@type'
FROM MyTable
FOR XML PATH('BOMLine'), TYPE)
FROM MyTable GROUP BY PID
FOR XML PATH('BOM'), TYPE, ROOT('BOMs'))
FROM MyTable
FOR XML PATH('Item'), TYPE)
select @test
任何人都可以帮我吗?顺便说一句,我正在使用SQL Server 2008。 非常感谢。
祝你好运, 韦斯
答案 0 :(得分:0)
您需要最外层查询中的group by
,并且您需要将子查询与PID
上的外部查询相关联。
PID
中的额外BOM
不需要from子句。
select T1.PID as '@Code',
(
select T1.PID as '@code',
(
select T2.CID as '@type'
from dbo.MyTable as T2
where T1.PID = T2.PID
for xml path('BOMLine'), type
)
for xml path('BOM'), root('BOMs'), type
)
from dbo.MyTable as T1
group by T1.PID
for xml path('Item')