考虑以下SQL:
;WITH XMLNAMESPACES(DEFAULT 'http://www.mynamespace.co.uk')
,CTE_DummyData AS (
select id=1
)
select TOP 1
[@ID]=1,
(select top 1 [@ID] = 1 FROM CTE_DummyData FOR XML PATH ('Child'), TYPE)
from CTE_DummyData
FOR XML PATH ('Parent')
返回xml:
<Parent xmlns="http://www.mynamespace.co.uk" ID="1">
<Child xmlns="http://www.mynamespace.co.uk" ID="1" />
</Parent>
我需要的是仅在根元素上使用xmlns声明返回xml。例如:
<Parent xmlns="http://www.mynamespace.co.uk" ID="1">
<Child ID="1" />
</Parent>
有办法做到这一点吗?
注意: 上面的SQL是对实际代码的极端简化,它产生了一个复杂的文档,所以如果不给我几天额外的工作,那么从FOR XML PATH改变并不是一个真正的选择。要明确整个文件的最高层需要有NS,所有孩子都应该没有。
答案 0 :(得分:2)
您可以使用"query from hell"
;with CTE_DummyData AS (
select id=1
)
select 1 as tag,
0 as parent,
'http://www.mynamespace.co.uk' as [Parent!1!xmlns],
id as [Parent!1!ID],
null as [Child!2!ID]
from CTE_DummyData
union all
select top 1
2,
1,
null,
null,
id
from CTE_DummyData
for xml explicit
答案 1 :(得分:1)
您可以使用UDF生成子节点。 E.g。
ALTER FUNCTION [dbo].[udf_get_child_section] (
@serviceHeaderId INT
)
RETURNS XML
BEGIN
DECLARE @result XML;
SELECT @result =
(
SELECT 1 AS 'ChildElement'
FOR XML PATH('Child')
)
RETURN @result
END
GO
DECLARE @Ids TABLE
(
ID int
)
INSERT INTO @Ids
SELECT 1 AS ID
UNION ALL
SELECT 2 AS ID
;WITH XMLNAMESPACES (DEFAULT 'http://www...com/content')
SELECT
[dbo].[udf_get_child_section](ID)
FROM
@Ids
FOR XML PATH('Parent')