我想要输出
<CustomerName>
<Customer id='1'>
<Name>xyz</Name>
</Customer>
<Customer id='2'>
<Name>Abc</Name>
</Customer>
</CustomerName>
这个输出我写了SP
SELECT
'' AS [CustomerName],
(SELECT
Name[Customer/Name]
FOR XML PATH(''), TYPE) AS[CustomerName/Customer]
FOR XML PATH('')
无法添加Id属性,请帮帮我
答案 0 :(得分:1)
试试这个:
DECLARE @tblCust TABLE(id INT, CustomerName VARCHAR(100));
INSERT INTO @tblCust VALUES
(1,'xyz')
,(2,'Abc');
SELECT id AS [@id]
,CustomerName AS [Name]
FROM @tblCust
FOR XML PATH('Customer'),ROOT('CustomerName')
这是结果
<CustomerName>
<Customer id="1">
<Name>xyz</Name>
</Customer>
<Customer id="2">
<Name>Abc</Name>
</Customer>
</CustomerName>
答案 1 :(得分:1)
SELECT [@id] = t.id, [Name] = t.name
FROM (
VALUES (1, 'name'), (2, 'name2')
) t (id, name)
FOR XML PATH('Customer'), ROOT('CustomerName')