Sql server 具有Listnode和结构的T-SQL XML结果
我有以下表格结构: 顾客:Sql server 具有Listnode和结构的T-SQL XML结果,sql-server,xml,tsql,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="ht
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>
为了进一步处理,我必须知道列表节点(Contact)的结构。因此,如果客户没有联系人(如第二个条目),我必须知道客户节点有哪些字段/列
有人知道如何解决这个问题吗?如果我正确理解了您的意思,那么如果没有联系人,您将不得不创建一个虚拟行
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>
里奇里奇·里奇
我的城市
试验
123123
伯尼·伯特尔
我的小镇
如果我理解正确,那么如果没有联系人,您将不得不创建一个虚拟行
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>
里奇里奇·里奇
我的城市
试验
123123
伯尼·伯特尔
我的小镇