我必须以下面的格式从SQL Server Stored Proc返回XML:
<Customer1>
<Policy1></Policy1>
<Policy2></Policy2>
</Customer1>
<Customer2>
<Policy1></Policy1>
<Policy2></Policy2>
<Policy3></Policy3>`
<Customer2>
.......
问题是我的Query为每一行创建了<Customer>
个节点。
答案 0 :(得分:0)
每当您看到编号名称( Policy1,Policy2 ... 或 Customer1,Customer2 )时,您可以确定,设计不良!
在您的情况下,似乎您希望将列值用作元素名称。这是你真的不应该做的事情!
假设有一个带有ID和Name的客户表以及一个带有ID,CustomerID和Number的策略表,它可能如下所示:
DECLARE @customer TABLE(ID INT,Name VARCHAR(100));
INSERT INTO @customer VALUES(1,'cust 1'),(2,'cust 2'),(3,'cust 3');
DECLARE @policy TABLE(ID INT,CustomerID INT,Number VARCHAR(100));
INSERT INTO @policy VALUES
(1,1,'p1 for c1'),(2,1,'p2 for c1')
,(3,2,'p1 for c2'),(4,2,'p2 for c2'),(5,2,'p3 for c2')
--no policy for c3
SELECT ID AS [@id]
,Name AS [@name]
,(
SELECT ID AS [@id]
,Number AS [@number]
FROM @policy AS p
WHERE p.CustomerID=c.ID
FOR XML PATH('policy'),ROOT('policies'),TYPE
)
FROM @customer AS c
FOR XML PATH('Customer')
结果
<Customer id="1" name="cust 1">
<policies>
<policy id="1" number="p1 for c1" />
<policy id="2" number="p2 for c1" />
</policies>
</Customer>
<Customer id="2" name="cust 2">
<policies>
<policy id="3" number="p1 for c2" />
<policy id="4" number="p2 for c2" />
<policy id="5" number="p3 for c2" />
</policies>
</Customer>
<Customer id="3" name="cust 3" />
你可以让,ROOT('policies')
离开(不推荐)