2017-11-18 292 views
3

我尝试使用SSIS包将一个csv文件导入到SQL Server表中时,出现了一个非常特殊的情况。 csv文件中的数据可以包含双引号和逗号。因此,带逗号的数据用双引号引起来,双引号用额外的双引号转义。我使用了文本限定符来成功处理最初的周围引号。但是,在某些情况下,数据格式化的格式类似于我无法处理的“”“Anne”“,Annabelle”。数据中额外的双引号似乎会导致逗号终止该字段。我试图使用派生列转换来替换那些可能不会导致问题的其他东西的双引号,但无济于事。是否有其他人遇到此问题并找到了解决方法或解决方法?使用SSIS和数据中的多个双引号将csv文件导入到SQL Server中

+0

你能提供一个示例文件吗?即使它只包含标题和一个数据行。否则,我可以给你一个类似案件的一般解决方案。 – Hadi

回答

1

如果你从这些领域失去了引号OK,一个简单的脚本任务处理您的文件导入,将工作之前(下面创建一个新的文件,“_Processed”添加到文件名):

public void Main() 
{ 
    System.IO.StreamReader reader = null; 
    System.IO.StreamWriter writer = null; 

    try 
    { 
     string filepath = Dts.Variables["User::Filepath"].Value.ToString(); 

     reader = new System.IO.StreamReader(filepath); 

     string fileText = reader.ReadToEnd(); 

     string newFilepath = 
      System.IO.Path.Combine(
       System.IO.Path.GetDirectoryName(filepath), 
       System.IO.Path.GetFileNameWithoutExtension(filepath) + "_Processed" + System.IO.Path.GetExtension(filepath) 
      ); 

     if (System.IO.File.Exists(newFilepath)) 
     { 
      System.IO.File.Delete(newFilepath); 
     } 

     writer = new System.IO.StreamWriter(newFilepath); 

     writer.Write(fileText.Replace("\"\"", "")); 

     Dts.TaskResult = (int)ScriptResults.Success; 
    } 
    catch (Exception ex) 
    { 
     Dts.Events.FireError(0, "Script Task", ex.Message, string.Empty, 0); 
    } 
    finally 
    { 
     if (reader != null) 
     { 
      writer.Close(); 
      writer.Dispose(); 
     } 

     if (writer != null) 
     { 
      writer.Close(); 
      writer.Dispose(); 
     } 
    } 
} 

如果你想保留的报价,我会改变:

writer.Write(fileText.Replace("\"\"", "")); 

喜欢的东西:

writer.Write(fileText.Replace("\"\"", "[double quote removed]")); 

然后,您可以将实际的双引号放回到派生列转换中。

对于所有这些,您只需使用标准的平面文件连接,并使用逗号作为分隔符,并使用"作为文本限定符。

相关问题