1

我有一个表,其中有一列是 xml 类型的。我必须从该表中提取数据并将数据加载到另一个环境中。我正在使用 bcp 来提取和加载目标表,但是当我将它们 bcp 到目标表中时,有一些特殊字符会导致一些问题。有什么解决方法吗

谢谢本

4

1 回答 1

3

定制的 CLR-SP 为我提供了最佳解决方案。现在我可以直接将 XML 类型的数据从 TSQL 写入文件,前提是 SQL 服务帐户有权访问该文件。这允许使用简单的语法:

exec dbo.clr_xml2file @xml, @path, @bool_overwrite

SP:

CREATE PROCEDURE [dbo].[clr_xml2file]
    @xml [xml],
    @file [nvarchar](max),
    @overwrite [bit]
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [CLR_FileIO].[FreddyB.FileIO].[Xml2File]

CLR DLL 的 C#:

using System;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using Microsoft.SqlServer.Server;

namespace FreddyB
{  
  public class FileIO
  {
    public static void Xml2File(
      SqlXml xml, 
      SqlString sFile, 
      SqlBoolean bOverwrite
    ) {

      SqlPipe sqlpipe = SqlContext.Pipe;
      try
      {
        if (xml == null || xml.IsNull || xml.Value.Length == 0) {
          sqlpipe.Send("Cannot write empty content to file : \n\t"
            +sFile.Value);
          return;
        }

        if (File.Exists(sFile.Value) & bOverwrite.IsFalse) {
          sqlpipe.Send("File already exists : \n\t"+sFile.Value);
          return;
        }

        int iFileSize = 0;
        FileStream fs = null;
        try {
          byte[] ba = Encoding.UTF8.GetBytes(xml.Value);
          iFileSize = ba.Length;

          fs = new FileStream(sFile.Value, FileMode.Create, FileAccess.Write);
          fs.Write(ba, 0, ba.Length);

          sqlpipe.Send("Wrote "
            +String.Format("{0:0,0.0}",iFileSize/1024)
            +" KB to : \n\t"
            +sFile.Value);
        }
        catch (Exception ex) 
        {
          sqlpipe.Send("Error as '"
            +WindowsIdentity.GetCurrent().Name
            +"' during file write : \n\t"
            +ex.Message);
          sqlpipe.Send("Stack trace : \n"+ex.StackTrace);
        }
        finally
        {
          if (fs != null) {
            fs.Close();
          }
        }
      }
      catch (Exception ex)
      {
        sqlpipe.Send("Error writing to file : \n\t"
          +ex.Message);
      }
    }
  }
}
于 2009-01-16T17:03:29.170 回答