How to convert records in a table to xml format using T-SQL?

前端 未结 3 1926
渐次进展
渐次进展 2020-12-14 01:19

I\'ve got a simple table and want to store its content into a xml on the harddrive. There should be one root element for the whole table, one element per table row and one c

3条回答
  •  忘掉有多难
    2020-12-14 02:04

    And if you need more control over how the resulting XML looks like, check out the new FOR XML PATH statement in SQL Server 2005 and newer.

    A statement like this (based on the infamous Northwind database):

    SELECT 
       CustomerID as "@CustomerID",
       CompanyName,
       Address as "address/street",
       City as "address/city",
       Region as "address/region",
       PostalCode as "address/zip",
       Country as "address/country",
       ContactName as "contact/name",
       ContactTitle as "contact/title",
       Phone as "contact/phone", 
       Fax as "contact/fax"
    FROM Customers
    FOR XML PATH('Customer')
    

    will result in an output like this:

      
        Alfreds Futterkiste
        
    Obere Str. 57 Berlin 12209 Germany
    Maria Anders Sales Representative 030-0074321 030-0076545

    That's rather tricky to get any other way....

    Marc

提交回复
热议问题