0

我有以下表格和内容:

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。这将不胜感激。

最好的问候,韦斯

4

1 回答 1

0

您需要group by最外层查询中的 ,并且需要使您的子查询与 上的外部查询相关联PID
额外PID的 inBOM不需要 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')
于 2013-10-21T15:15:57.310 回答