Tsql 防止XML中出现行

Tsql 防止XML中出现行,tsql,subquery,for-xml-path,Tsql,Subquery,For Xml Path,我有以下表格和内容: 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

我有以下表格和内容:

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>
有人能帮我吗?顺便说一下,我正在使用SQL Server 2008。 我们将不胜感激

致以最良好的祝愿,
Wes

您需要在最外层查询中使用
分组依据
,并且需要使子查询与
PID
上的外部查询相关联
BOM
中的额外
PID
不需要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')
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')