Question

I have the following table and content:

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)

From this I need to create the following XML layout:

<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>

I'm trying to achieve this with the following statement which gives me far too much lines and duplicates:

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

Can anyone help me with this? I'm using SQL Server 2008 by the way. It would be greatly appreciated.

Best regards, Wes

Was it helpful?

Solution

You need the group by in the outermost query and you need to make your sub-query correlated with the outer query on PID.
The extra PID in BOM does not need a from clause.

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top