How to export XML using a SQL Server query?

后端 未结 2 2060
迷失自我
迷失自我 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 08:20

    I've had the same problem and I've created a .NET CLR that exports XML to a file:

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.SqlTypes;
    using Microsoft.SqlServer.Server;
    using System.Text;
    using System.Xml;
    using System.IO;
    
    
    public sealed class StringWriterWithEncoding : StringWriter
    {
        private readonly Encoding encoding;
    
        public StringWriterWithEncoding(Encoding encoding)
        {
            this.encoding = encoding;
        }
    
        public override Encoding Encoding
        {
            get { return encoding; }
        }
    }
    
    public partial class StoredProcedures
    {
        [Microsoft.SqlServer.Server.SqlProcedure]
        public static void XMLExport (SqlXml InputXml, SqlString OutputFile)
        {
            try
            {
                if (!InputXml.IsNull && !OutputFile.IsNull)
                {               
    
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(InputXml.Value);
    
                    StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.UTF8);
                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        Indent = true,
                        IndentChars = "  ",
                        NewLineChars = "\r\n",
                        NewLineHandling = NewLineHandling.Replace,
                        Encoding = System.Text.Encoding.UTF8
                    };
    
                    using (XmlWriter writer = XmlWriter.Create(sw, settings))
                    {
                        doc.Save(writer);
                    }
    
    
                    System.IO.File.WriteAllText(OutputFile.ToString(), sw.ToString(), System.Text.Encoding.UTF8);
                }
                else
                {
                    throw new Exception("Parameters must be set");
                }
            }
            catch
            {
                throw;
            }
        }
    }
    

    Here's an example how to use it:

    DECLARE @x xml
    SET @x = '12'
    
    EXEC dbo.XmlExport @x, 'c:\test.xml'
    

    And the output is a nicely formatted XML file:

    
    
      1
      2
    
    

提交回复
热议问题