我有一个使用 FOR XML EXPLICIT 的 SQL 查询:
declare @address table
(
AddressID int,
AddressType varchar(12),
Address1 varchar(20),
Address2 varchar(20),
City varchar(25)
)
insert into @address
select 1, 'Home', 'abc', 'xyz road', 'RJ' union all
select 2, 'Office', 'temp', 'ppp road', 'RJ' union all
select 3, 'Temp', 'eee', 'olkiu road', 'CL'
SELECT
1 AS Tag,NULL AS Parent,
0 AS 'AddressCollection!1!Sort!hide',
NULL AS 'AddressCollection!1!',
NULL AS 'Address!2!AddressID',
NULL AS 'Address!2!AddressType!Element',
NULL AS 'Address!2!Address1!Element',
NULL AS 'Address!2!Address2!Element',
NULL AS 'Address!2!City!Element'
UNION ALL
SELECT
2 AS Tag,1 AS Parent,AddressID * 100,NULL,
AddressID,AddressType, Address1, Address2, City
FROM @address
ORDER BY [AddressCollection!1!Sort!hide]
FOR XML EXPLICIT
XML 结果是:
<AddressCollection>
<Address AddressID="1">
<AddressType>Home</AddressType>
<Address1>abc</Address1>
<Address2>xyz road</Address2>
<City>RJ</City>
</Address>
<Address AddressID="2">
<AddressType>Office</AddressType>
<Address1>temp</Address1>
<Address2>ppp road</Address2>
<City>RJ</City>
</Address>
<Address AddressID="3">
<AddressType>Temp</AddressType>
<Address1>eee</Address1>
<Address2>olkiu road</Address2>
<City>CL</City>
</Address>
</AddressCollection>
如何向元素添加属性?我已经正确地将它们添加到父标签上,但我不知道如何将它们添加到元素标签中。
我需要这样的东西:
<AddressCollection>
<Address AddressID="1">
<AddressType>Home</AddressType>
<Address1>abc</Address1>
<Address2>xyz road</Address2>
<City status="modified">RJ</City>
</Address>
<Address AddressID="2">
<AddressType status="modified">Office</AddressType>
<Address1>temp</Address1>
<Address2>ppp road</Address2>
<City>RJ</City>
</Address>
<Address AddressID="3">
<AddressType>Temp</AddressType>
<Address1 status="modified">eee</Address1>
<Address2>olkiu road</Address2>
<City>CL</City>
</Address>
</AddressCollection>