2017-11-18 281 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]")); 

然後,您可以將實際的雙引號放回到派生列轉換中。

對於所有這些,您只需使用標準的平面文件連接,並使用逗號作爲分隔符,並使用"作爲文本限定符。

相關問題