使用SQL命令编写XML

时间:2015-09-01 07:23:46

标签: mysql sql xml sqlcommand

我遇到了SQLCommand for XML的问题。其实我是新手

我有两张桌子:

  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

    {{2} }

现在,我想用sql命令选择和创建xml,尤其是“for xml”。如何编写sql命令?

结果,也许就像这样

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命令,但没有使用

 <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>

实际上,结果与我的目的不一样。

1 个答案:

答案 0 :(得分: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')