2016-08-11 68 views
1

請幫助我處理事情。用於XML命名空間的SQL語句

我有2個表:

#head 

PARAM1 PARAM2 PARAM3 
------ ------ ------ 
AAA BBB CCC 

#body 

NAME     SEX     EMAIL 
-------------------- -------------------- -------------------- 
Tania    Female    [email protected] 
Sergey    male     [email protected] 

爲了使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>[email protected]</EMAIL> 
    </BODY> 
    <BODY> 
    <NAME>Sergey</NAME> 
    <SEX>male</SEX> 
    <EMAIL>[email protected]</EMAIL> 
    </BODY> 
</HEAD> 

預期的結果是:

<ns0:HEAD Param1="AAA" Param2="BBB" Param3="CCC" xmlns:ns0="http://google.example"> 
    <BODY> 
    <NAME>Tania</NAME> 
    <SEX>Female</SEX> 
    <EMAIL>[email protected]</EMAIL> 
    </BODY> 
    <BODY> 
    <NAME>Sergey</NAME> 
    <SEX>male</SEX> 
    <EMAIL>[email protected]</EMAIL> 
    </BODY> 
</ns0:HEAD> 

有誰知道如何達到預期的結果?

在此先感謝您的幫助!

+0

標籤 「SQL」 是不夠的!請編輯您的問題以標記實際的DBMS(供應商和版本)... – Shnugo

回答

2

如果這是SQL的服務器(你的代碼看起來是這樣),你可以試試這個:

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','[email protected]') 
,('Sergey','male','[email protected]'); 
GO 

- 這將命名空間添加到身體好。不應該做的問題,這是衆所周知的問題...

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'); 

--clean-最多

GO 
drop table #head; 
drop table #body; 
+0

感謝您的幫助! –