我正在使用FOR XML PATH
从SQL Server 2008 R2运行查询。我唯一的问题是我想要显示所有元素,即使它们是NULL并且我希望空(或null)元素返回为
<MyElement />
不是
<MyElement></MyElement>
答案 0 :(得分:5)
您可以使用for xml
在字段列表中查询子查询中的字段,创建两个版本的空元素。
declare @T table
(
ID int identity primary key,
Name nvarchar(10)
)
insert into @T(Name)
select 'Name 1' union all
select null union all
select 'Name 2'
select ID,
(select Name as '*' for xml path(''), type) as Name,
(select Name as '*' for xml path('Name'), type)
from @T
for xml path('row')
结果:
<row>
<ID>1</ID>
<Name>Name 1</Name>
<Name>Name 1</Name>
</row>
<row>
<ID>2</ID>
<Name></Name>
<Name />
</row>
<row>
<ID>3</ID>
<Name>Name 2</Name>
<Name>Name 2</Name>
</row>
答案 1 :(得分:2)
DECLARE @t TABLE (
id INT, Name1 VARCHAR(20),
Value1 VARCHAR(20), Name2 VARCHAR(20),
Value2 VARCHAR(20))
INSERT INTO @t (id, name1, value1, name2, value2)
SELECT 1, 'PrimaryID', NULL, 'LastName', 'Abiola' UNION ALL
SELECT 2, 'PrimaryID', '200', 'LastName', 'Aboud'
SELECT
(
SELECT
name1 AS 'Parameter/Name',
value1 AS 'Parameter/Value'
FROM @t t2 WHERE t2.id = t.id
FOR XML PATH(''), ELEMENTS XSINIL, TYPE
),
(
SELECT
name2 AS 'Parameter/Name',
value2 AS 'Parameter/Value'
FROM @t t2 WHERE t2.id = t.id
FOR XML PATH(''), TYPE
)
FROM @t t
FOR XML PATH('T2Method')
<T2Method>
<Parameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>PrimaryID</Name>
<Value xsi:nil="true" />
</Parameter>
<Parameter>
<Name>LastName</Name>
<Value>Abiola</Value>
</Parameter>
</T2Method>
<T2Method>
<Parameter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>PrimaryID</Name>
<Value>200</Value>
</Parameter>
<Parameter>
<Name>LastName</Name>
<Value>Aboud</Value>
</Parameter>
</T2Method>