2015-09-01 49 views
0

我對SQLCommand for XML有問題。其實我新手使用SQL命令編寫XML

我有2個表:

  1. Customer_BSM

     
    id_Cust | Name | Omset | Colour | seq 
    --------------------------------------------- 
    1001 | Ali  | 10  | Black | 1 
    2001 | Bhudi | 5  | Red  | 2 
    3001 | charlie | 20  | yellow | 3 
    
  2. address_BSM

     
    id_cust | Address | no1 | no2 
    ----------------------------------- 
    1001 | Jln 1 | 1A  | 2A 
    1001 | Jln 2 | 1B  | 2B 
    2001 | street 1 | S1  | S2 
    3001 | gang A | AG  | BG 
    

現在,我要選擇和創建SQL命令的XML ,特別是使用「for xml」。如何編寫sql命令?

的結果,也許這樣

<customer_BSM id="1"> 
    <id_cust>1001<id_cust> 
    <Name>Ali</Name> 
    <omset>10</omset> 
    <colour>black</colour> 
    <addres_bsm> 
     <address>jln 1</address> 
     <no1>1A</no1 
     <no2>2A</no2> 
    </addres_bsm> 
    <addres_bsm> 
     <address>jln 2</address> 
     <no1>1B</no1 
     <no2>2B</no2> 
    </addres_bsm> 
</customer_BSM> 
<customer_BSM id="2"> 
    <id_cust>2001<id_cust> 
    <Name>Bhudi</Name> 
    <omset>5</omset> 
    <colour>red</colour> 
    <addres_bsm> 
     <address>street 1 </address> 
     <no1>S1</no1 
     <no2>S2</no2> 
    </addres_bsm> 
</customer_BSM> 
<customer_BSM id="3"> 
    <id_cust>3001<id_cust> 
    <Name>Charlie</Name> 
    <omset>20</omset> 
    <colour>Yellow</colour> 
    <addres_bsm> 
     <address>gang A</address> 
     <no1>AG</no1 
     <no2>BG</no2> 
    </addres_bsm> 
</customer_BSM> 

我用這個SQL命令,但沒有工作

SELECT *, (
    SELECT * 
    FROM [address_bsm] A INNER JOIN [customer_bsm] B 
    ON a.id_cust = b.id_cust 
    FOR XML PATH ('Address_bsm')) 
FROM [customer_bsm] 
FOR XML PATH 

其實,結果還是一樣不跟我的目的。

回答

0

我只能用MSSQL進行測試,但是SQL應該非常相似。

SELECT c.[id_Cust] 
     ,[Name] 
     ,[Omset] 
     ,[Colour] 
     ,[seq] 
     ,(SELECT a.[Address],a.[no1],a.[no2] FROM address_BSM a 
     WHERE a.id_cust = c.id_cust 
    FOR XML PATH ('address_bsm'), TYPE) 
    FROM [dbo].[Customer_BSM] c 
    FOR XML PATH ('customer_bsm') 
+0

謝謝你的回答..我在MS SQL中嘗試你的代碼,並且我得到了結果。也許你想念ID,代表表中的SEQ。有你和想法嗎?最好的問候 – bneo

+0

只是嘗試寫入您的選擇「seq AS [@id]」的第一個條目,這應該讓seq的值成爲名爲「id」的頂級節點的歸屬... – Shnugo

+0

謝謝SQLDBA&Shugo。 .. – bneo