请帮我一件事。
我有两张桌子:
#head
PARAM1 PARAM2 PARAM3
------ ------ ------
AAA BBB CCC
#body
NAME SEX EMAIL
-------------------- -------------------- --------------------
Tania Female mail@femail.com
Sergey male mail@mail.com
制作XML我正在使用下一个查询:
Query:
DECLARE @XML VARCHAR(1000)
DECLARE @xmlns VARCHAR(1000)
SET @xmlns = 'http://google.example'
SET @XML =
REPLACE(
(
SELECT TOP 1
Param1 as 'Param1',
Param2 as 'Param2',
Param3 as 'Param3',
@XMLNS AS xmlns,
(
SELECT
NAME as 'NAME',
SEX as 'SEX',
EMAIL as 'EMAIL'
FROM
#body AS BODY
FOR XML PATH('BODY'),TYPE
)
FROM
#head AS HEAD
FOR XML AUTO
),' xmlns=""',''
)
SELECT CAST(@XML AS XML) AS myXML
当前结果是:
<HEAD xmlns="http://google.example" Param1="AAA" Param2="BBB" Param3="CCC">
<BODY>
<NAME>Tania</NAME>
<SEX>Female</SEX>
<EMAIL>mail@femail.com</EMAIL>
</BODY>
<BODY>
<NAME>Sergey</NAME>
<SEX>male</SEX>
<EMAIL>mail@mail.com</EMAIL>
</BODY>
</HEAD>
预期结果是:
<ns0:HEAD Param1="AAA" Param2="BBB" Param3="CCC" xmlns:ns0="http://google.example">
<BODY>
<NAME>Tania</NAME>
<SEX>Female</SEX>
<EMAIL>mail@femail.com</EMAIL>
</BODY>
<BODY>
<NAME>Sergey</NAME>
<SEX>male</SEX>
<EMAIL>mail@mail.com</EMAIL>
</BODY>
</ns0:HEAD>
有人知道如何达到预期结果吗?
答案 0 :(得分:2)
如果这是SQL-Server(您的代码如下所示),您可以尝试这样做:
create table #head(PARAM1 varchar(100), PARAM2 varchar(100), PARAM3 varchar(100));
insert into #head values
('AAA','BBB','CCC');
create table #body(NAME varchar(100), SEX varchar(100), EMAIL varchar(100));
insert into #body values
('Tania','Female','mail@femail.com')
,('Sergey','male','mail@mail.com');
GO
- 这也会将命名空间添加到BODY。不应该出问题,这是众所周知的问题......
WITH XMLNAMESPACES('http://google.example' AS ns0)
SELECT PARAM1 AS [@Param1]
,PARAM2 AS [@Param2]
,PARAM3 AS [@Param3]
,(
SELECT NAME,SEX,EMAIL
FROM #body
FOR XML PATH('BODY'),TYPE
)
FROM #head
FOR XML PATH('ns0:HEAD');
- 如果你想避免使用内部命名空间,你可以试试这个;
DECLARE @bodyXML XML=
(SELECT NAME,SEX,EMAIL
FROM #body
FOR XML PATH('BODY'),TYPE
);
WITH XMLNAMESPACES('http://google.example' AS ns0)
SELECT PARAM1 AS [@Param1]
,PARAM2 AS [@Param2]
,PARAM3 AS [@Param3]
,@bodyXML
FROM #head
FOR XML PATH('ns0:HEAD');
- 清理
GO
drop table #head;
drop table #body;