【问题标题】:Prevent lines appearing in XML防止在 XML 中出现行
【发布时间】:2013-10-21 14:37:24
【问题描述】:

我有以下表格和内容:

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

最好的问候, 韦斯

【问题讨论】:

    标签: tsql subquery for-xml-path


    【解决方案1】:

    您需要在最外层查询中使用group by,并且您需要使您的子查询与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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      相关资源
      最近更新 更多