SSIS:使用脚本任务将csv文件(文件分隔符为,文本限定符为“)导入sql服务器表

时间:2018-10-03 10:14:22

标签: sql-server csv text ssis delimiter

我想知道在使用脚本任务导入时如何实现文本限定符。下面是我的代码。我只能使用定界符,而不能使用文本限定符。因此,我也在表中加载了双引号。

        public void Main()
    {
        // TODO: Add your code here
        string SourceFolderPath = Dts.Variables["User::SourceFolder"].Value.ToString();
        string FileExtension = Dts.Variables["User::FileExtension"].Value.ToString();
        string FileDelimiter = Dts.Variables["User::FileDelimiter"].Value.ToString();
        string TableName = Dts.Variables["User::DestinationTable"].Value.ToString();


        SqlConnection myADONETConnection = new SqlConnection();
        myADONETConnection = (SqlConnection)
        (Dts.Connections["PEGASUS.AdventureWorks1"].AcquireConnection(Dts.Transaction) as SqlConnection);

       string[] fileEntries = Directory.GetFiles(SourceFolderPath, "*" + FileExtension);
            foreach (string fileName in fileEntries)
            {
                int counter = 0;
                string line;
                string ColumnList="";
                MessageBox.Show(fileName);

                System.IO.StreamReader SourceFile = new System.IO.StreamReader(fileName);
                while ((line = SourceFile.ReadLine()) != null)
                {
                    if (counter == 0)
                    {
                        ColumnList = "[" +(line.Replace(FileDelimiter, "],[").Replace("\"", ""))+ "]";
                        MessageBox.Show(ColumnList.ToString());
                    }
                    else
                    {
                        MessageBox.Show("pass 2");
                        string query = "Insert into " + TableName + " (" + ColumnList + ") ";
                        query += "VALUES('" + line.Replace(FileDelimiter, "','") + "')";
                        MessageBox.Show("pass 3");

                        //MessageBox.Show(query.ToString());
                        SqlCommand cmd = new SqlCommand(query, myADONETConnection);
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("pass 4");
                    }

                    counter++;
                }

                SourceFile.Close();
                Dts.TaskResult = (int)ScriptResults.Success;
            }
        }   

CSV input This is expected output

上面是输入和预期输出。

0 个答案:

没有答案