2016-12-06 55 views
2

我有樣本數據如何格式化XML代碼時,數據在一條線來

DECLARE @Table1 TABLE (users int, ts int, name varchar(10), [1] int); 

INSERT INTO @Table1 (users, ts, name, [1]) 
VALUES (1, 1, 'Raj', 0), 
     (1, 3, 'maj', 2534), 
     (1, 10, 'yes', 1458); 

腳本

select 
    'test' as 'job/branch/FBEN/opcode', 
    users AS 'job/branch/FBEN/opcode', 
    name as 'job/branch/FBEN/opcode' 
from 
    @Table1 
where 
    ts = 1 
for xml path('xmlexecute'), elements; 

輸出:

<xmlexecute> 
    <job> 
    <branch> 
     <FBEN> 
     <opcode>test1Raj</opcode> 
     </FBEN> 
    </branch> 
    </job> 
</xmlexecute> 

我怎樣才能得到這樣代替?

<xmlexecute> 
    <job> 
    <branch> 
     <FBEN> 
     <opcode>test1Raj</opcode> 
     <opcode>1</opcode> 
     <opcode>Raj</opcode> 
     </FBEN> 
    </branch> 
    </job> 
</xmlexecute> 

如果我嘗試添加

select 
    'test' as 'job/branch/FBEN/opcode', 
    users AS 'job/branch/FBEN/opcode', 
    name as 'job/branch/FBEN/opcode', 
    [1] AS 'job/branch/FBEN/opcode/1' 
from 
    @Table1 
where 
    ts = 3 
for xml path('xmlexecute'), elements; 

我得到一個錯誤:

Msg 6850, Level 16, State 1, Line 14
Column name 'job/branch/FBEN/opcode/1' contains an invalid XML identifier as required by FOR XML; '1'(0x0031) is the first character at fault.

+0

檢查這個網址:http://stackoverflow.com/questions/34938591/for-xml-structure-with-two-parent-nodes-and-multiple-child-nodes –

回答

1

試試這樣說:

DECLARE @Table1 TABLE (users int, ts int, name varchar(10), [1] int); 

INSERT INTO @Table1 (users, ts, name, [1]) 
VALUES (1, 1, 'Raj', 0), 
     (1, 3, 'maj', 2534), 
     (1, 10, 'yes', 1458); 
select 
(
    select 
     'test' as [opcode] 
     ,'' 
     ,users AS [opcode] 
     ,'' 
     ,name as [opcode] 
     ,'' 
     ,[1] AS [opcode] 
    from 
     @Table1 
    where 
     ts = 1 
    for xml path('FBEN'),ROOT('branch'),TYPE 
) AS job 
FOR XML PATH('xmlexecute') 
; 

空節點,''之間您的opcode節點告訴XML引擎:該節點完成後,啓動一個新節點。這是必需的,如果你想放置幾個相同名字的節點。

結果

<xmlexecute> 
    <job> 
    <branch> 
     <FBEN> 
     <opcode>test</opcode> 
     <opcode>1</opcode> 
     <opcode>Raj</opcode> 
     <opcode>0</opcode> 
     </FBEN> 
    </branch> 
    </job> 
</xmlexecute> 
+0

我需要在我的要求中檢查這個解決方案@shnugo – mohan111

+0

第四列我怎麼樣;在使用第四列時仍然會出現同樣的錯誤 – mohan111

+0

@ mohan111我不知道你做了什麼,但看到我的更新。它正在工作......你問題中的'XPath'('[1] AS'job/branch/FBEN/opcode/1')無法工作。一個elementsname不能以數字開頭。也就是說,錯誤告訴你什麼。在你的問題*預期輸出*不包括這一列...不知道,如何以及在哪裏你想找到它... – Shnugo