How to export XML using a SQL Server query?

后端 未结 2 2112
迷失自我
迷失自我 2021-02-09 07:45

Let\'s say I have a table Employee like this

EmpID, EmpName

1    , hatem

and I write a query: select * from Employee for xm

2条回答
  •  半阙折子戏
    2021-02-09 07:58

    If you only need to store the XML and not do anything else to it, this is probably the easiest way to accomplish this - using straight simple ADO.NET:

    string query = "SELECT EmployeeID, LastName, FirstName, Title, BirthDate, HireDate FROM dbo.Employees FOR XML AUTO";
    
    using(SqlConnection _con = new SqlConnection("server=(local);database=Northwind;integrated security=SSPI;"))
    using (SqlCommand _cmd = new SqlCommand(query, _con))
    {
        _con.Open();
        string result = _cmd.ExecuteScalar().ToString();
        _con.Close();
    
        File.WriteAllText(@"D:\test.xml", result);
    }
    

    This will create a file D:\test.xml (or change that to match your system) and will put those XML tags into that file.

    The SqlCommand object also has a .ExecuteXmlReader() method which would return an XmlReader object to scan and manipulate the XML - not just return a string. Use whatever makes the most sense to you!

    PS: also, the output of FOR XML AUTO is a bit .... let's say ... suboptimal. It uses the dbo.Employee as it's main XML tag and so forth... with SQL Server 2008, I would strongly recommend you look into using FOR XML PATH instead - it allows you to tweak and customize the layout of the XML output.

    Compare your original XML output with FOR XML AUTO

    
    
    

    against this query - just to see the difference:

    SELECT 
        [EmployeeID] AS '@ID',
        [LastName], [FirstName],
        [Title],
        [BirthDate], [HireDate]
    FROM 
        [dbo].[Employees]
    FOR XML PATH('Employee'), ROOT('Employees')
    

    Output is:

    
      
        Davolio
        Nancy
        Sales Representative
        1948-12-08T00:00:00
        1992-05-01T00:00:00
      
      
        Fuller
        Andrew
        Vice President, Sales
        1952-02-19T00:00:00
        1992-08-14T00:00:00
      
    

提交回复
热议问题