【问题标题】:sql server bcp xml datasql server bcp xml 数据
【发布时间】:2010-10-01 14:58:48
【问题描述】:

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

谢谢 本

【问题讨论】:

    标签: sql sql-server xml bcp


    【解决方案1】:

    自定义 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);
          }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 2021-12-05
      • 2019-02-21
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多