Let\'s say I have a table Employee
like this
EmpID, EmpName
1 , hatem
and I write a query: select * from Employee for xm
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 = '1 2 '
EXEC dbo.XmlExport @x, 'c:\test.xml'
And the output is a nicely formatted XML file:
1
2