将数据库转换为具有特定格式的XML

时间:2016-11-07 12:52:58

标签: sql sql-server-2008

我有两个表格的数据库:Transactionfrom_person

我需要将其转换为指定格式,如下所示:

<transaction>                      
  <transaction_number>TRNWEB0147</transaction_number
  <transaction_location>felesteen</transaction_location>
  <date_transaction>2016-05-25T00:00:00</date_transaction>
  <from_funds_code>C</from_funds_code>
<from_person>                    
  <gender>M</gender>
  <title>Mr.</title>
  <first_name>Mohamed</first_name>
  <middle_name>Mohamed</middle_name>
  <prefix>AHMED</prefix>
  <last_name>yahia</last_name>
  <birth_date>1984-11-16T00:00:00</birth_date>
  <ssn>28411160225124</ssn>
</from_person>
</transaction>

我尝试执行此查询:

select tr.transactionnumber
      ,tr.transaction_location
      ,tr.transaction_description
      ,tr.date_transaction
      ,tr.teller
      ,tr.authorized
      ,tr.transmode_
      ,tr.amount_local
      ,(select fp.from_funds_code
              ,fp.from_country
          from from_person fp
         where fp.from_funds_code = tr.t_from_my_client
           for xml path(''), elements, type)
  from dbo. [ transaction ] tr
   for xml path(''), elements, type

但结果将采用以下格式:

  <transaction_number>TRNWEB0147</transaction_number
  <transaction_location>felesteen</transaction_location>
  <date_transaction>2016-05-25T00:00:00</date_transaction>
  <from_funds_code>C</from_funds_code>              
  <gender>M</gender>
  <title>Mr.</title>
  <first_name>Mohamed</first_name>
  <middle_name>Mohamed</middle_name>
  <prefix>AHMED</prefix>
  <last_name>yahia</last_name>
  <birth_date>1984-11-16T00:00:00</birth_date>
  <ssn>28411160225124</ssn>

我尝试了很多方法,但没有成功,请帮助。

1 个答案:

答案 0 :(得分:1)

请使用此查询。

SELECT transaction_number,transaction_location,date_transaction,from_funds_code,
(
    SELECT gender,title,first_name,middle_name,prefix,last_name,birth_date,ssn
    FROM from_person FP
    WHERE FP.FROM_FUNDS_CODE  =TR.T_FROM_MY_CLIENT 
    FOR XML PATH('from_person'), ELEMENTS, TYPE 
)
FROM dbo.[TRANSACTION] TR
FOR XML PATH('transaction'), ELEMENTS, TYPE