我的表包含三列:
[ID],[Name],[Value]
我选择的xml结果:
DECLARE @xml XML
SET @xml = (
SELECT
ID
,[Name]
,[Value]
FROM [CustomerDetails]
WHERE ID = 1
FOR XML PATH(''), ROOT('Customer')
)
SELECT @xml
我的选择返回带有多个ID属性的xml:
<Customer>
<ID>1</ID>
<Name>FirstName</Name>
<Value>firstName</Value>
<ID>1</ID>
<Name>LastName</Name>
<Value>lastName</Value>
<ID>1</ID>
<Name>Age</Name>
<Value>20</Value>
<ID>1</ID>
<Name>City</Name>
<Value>London</Value>
</Customer>
我需要下一个xml:
<Customer>
<ID>1</ID>
<Name>FirstName</Name>
<Value>firstName</Value>
<Name>LastName</Name>
<Value>lastName</Value>
<Name>Age</Name>
<Value>20</Value>
<Name>City</Name>
<Value>London</Value>
</Customer>
如何返回这种XML?
答案 0 :(得分:1)
我缩短了列的名称:
declare @id int = 1
select id, n, v from
(select @id id, null n, null v, 1 as rn from t
union
select null, n, v, 2 as rn from t
where id = @id
) t order by rn
for xml path(''), root('customer')
输出:
<customer><id>1</id><n>n1</n><v>v1</v><n>n2</n><v>v2</v><n>n3</n><v>v3</v></customer>