Listnode和结构

时间:2016-06-16 09:12:00

标签: sql-server xml tsql

我有以下表结构:

客户:

CustomerId  Name            City
1           Richie Rich     MyCity
2           Bernie Bertel   MyTown

联系人:

ContactId   CustomerId  Name    Telephone
1           1           Test    123123

我想在XML结构中得到如下结果:

<Customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Customers>
    <Name>Richie Rich</Name>
    <City>MyCity</City>
    <Contacts>
      <Contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Name>Test</Name>
        <Telephone>123123</Telephone>
      </Contact>
    </Contacts>
  </Customers>
  <Customers>
    <Name>Bernie Bertel</Name>
    <City>MyTown</City>
    <Contacts xsi:nil="true" />
  </Customers>
</Customers>

相应的T-SQL查询是:

SELECT 
    Name,
    City,
    (
        SELECT 
            Name,
            Telephone
        FROM Contacts
        WHERE (Customers.CustomerId = Contacts.CustomerId)
        FOR XML PATH ('Contact'), TYPE, ELEMENTS XSINIL
    ) AS Contacts
FROM Customers
FOR XML AUTO, ROOT('Customers'), TYPE, ELEMENTS XSINIL

为了进一步处理,我必须知道列表节点的结构(Contact)。因此,如果客户没有联系人(如第二个条目中那样),我必须知道客户节点有哪些字段/列。

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

如果我理解正确,那么如果没有联系人,你将不得不创建一个虚拟行;

SELECT 
    Name,
    City,
    (
        SELECT * FROM (
        SELECT 
            Name,
            Telephone
        FROM Contacts
        WHERE (Customers.CustomerId = Contacts.CustomerId)
        UNION ALL
        SELECT 
            NULL AS Name,
            NULL AS Telephone
        WHERE NOT EXISTS (SELECT 1 FROM Contacts WHERE Customers.CustomerId = Contacts.CustomerId)
        ) x
        FOR XML PATH ('Contact'), TYPE, ELEMENTS XSINIL
    ) AS Contacts
FROM Customers
FOR XML AUTO, ROOT('Customers'), TYPE, ELEMENTS XSINIL

产生这个;

<Customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Customers>
    <Name>Richie Rich</Name>
    <City>MyCity</City>
    <Contacts>
      <Contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Name>Test</Name>
        <Telephone>123123</Telephone>
      </Contact>
    </Contacts>
  </Customers>
  <Customers>
    <Name>Bernie Bertel</Name>
    <City>MyTown</City>
    <Contacts>
      <Contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Name xsi:nil="true" />
        <Telephone xsi:nil="true" />
      </Contact>
    </Contacts>
  </Customers>
</Customers>