繁体   English   中英

使用带有多个双引号的SSIS将csv文件导入SQL Server

[英]Importing csv file into SQL Server using SSIS with multiple double quotes in data

我尝试使用SSIS包将csv文件导入SQL Server表时,由于非常具体的情况而出现问题。 csv文件中的数据可以包含双引号和逗号。 因此,带有逗号的数据是双引号,双引号则使用额外的双引号进行转义。 我已经使用文本限定符来成功处理初始的周围引号。 但是,有些特殊情况下数据的格式类似于“安妮”,“安娜贝尔” ,我无法处理。 数据中的额外双引号似乎会导致逗号终止该字段。 我曾尝试使用派生列转换将这些双引号替换为可能不会导致问题的其他内容,但无济于事。 有没有其他人遇到过这个问题并找到了解决方案或解决方法?

如果您可以丢失这些字段中的引号,则在导入文件之前处理文件的简单脚本任务将起作用(以下创建一个新文件,其中“_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]"));

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM