如何在sql server(2005)中使用for xml-directive创建一个真正空的xml元素?
示例:
select
''
for xml path('element'), root('elements')
输出:
<elements><element></element></elements>
但我真正想要的是:
<elements><element /></elements>
答案 0 :(得分:1)
添加type指令,然后在子查询中运行它。
像这样:
select
(
select
''
for xml path('element'), type
)
for xml path('elements')
答案 1 :(得分:0)
select
null
for xml path('element'), root('elements')
答案 2 :(得分:0)
您只需要知道该值是否为空,例如:ISNULL(Field, '')
像这样:
DECLARE @T table
(
ID int identity primary key,
Name nvarchar(10)
)
INSERT INTO @T (Name)
SELECT 'Name1'
UNION ALL
SELECT NULL
-- @Result1
SELECT ID AS Id
,ISNULL(Name, '') AS Name
FROM @T
FOR XML PATH ('Person')
-- @Result2
DECLARE @Result2 XML = ( SELECT
ID AS Id
,ISNULL(Name, '') AS Name
FROM @T
FOR XML PATH ('Person'))
SELECT @Result2;
结果1:
<Person>
<Id>1</Id>
<Name>Name1</Name>
</Person>
<Person>
<Id>2</Id>
<Name></Name>
</Person>
结果2:
<Person>
<Id>1</Id>
<Name>Name1</Name>
</Person>
<Person>
<Id>2</Id>
<Name />
</Person>