在单个sqlcommand中执行多个插入时捕获错误的命令行

时间:2011-10-19 07:09:41

标签: c# sql-server sqlcommand

我必须在我的应用程序的单个sql中自动执行多个sqlcommand插入命令,并且我必须保留不执行云的插入命令(因为已执行 c#的sqlcommand 中的错误)。 顺便说一句,我不希望错误抑制继续执行查询。

有什么建议吗?

谢谢

3 个答案:

答案 0 :(得分:2)

在SQL语句中使用try catch

请参阅this MSDN linkCodeProject link

答案 1 :(得分:1)

你可以对所有可用的命令执行for或for循环执行:在这个循环中你设置一个try catch并在catch块中记录/报告异常但不抛出这样循环将继续下一次迭代

请注意,您也可以使用SqlBulk对象以类似于您描述的方式执行许多插入。

修改

如果速度慢,你绝对可以使用SqlBulkCopy:点击此处查看分步示例:Bulk Insert into SQL from C# App

答案 2 :(得分:0)

这很有用

void ConvertCsv(string sourcePath, string ResultPath)
{


    #region
    using (StreamReader sr = new StreamReader(sourcePath))
    {
        using (StreamWriter sw = new StreamWriter(ResultPath))
        {
            sw.WriteLine(@"DECLARE @er NVARCHAR(MAX)='',@i INT=0 BEGIN  TRY");
            if (sr.Peek() >= 0)
            {
                string currentLine = sr.ReadLine();

                while (currentLine.Trim() == "" && sr.Peek() >= 0)
                    currentLine = sr.ReadLine();
                if (currentLine.Trim() == "")
                {
                    //error :the file is empty
                }
                sw.WriteLine(currentLine);

            }

            while (sr.Peek() >= 0)
            {
                string currentLine = sr.ReadLine();

                if (currentLine.Trim() == "")
                    continue;
                if (currentLine.Trim().StartsWith("INSERT"))
                {
                    while (!currentLine.Trim().StartsWith("INSERT"))
                        currentLine += sr.ReadLine();
                    currentLine = @"END TRY
                                                    BEGIN CATCH
                                                    SELECT @er+=','+LTRIM(RTRIM(STR(ERROR_LINE()))),@i+=1
                                                END CATCH BEGIN  TRY" + Environment.NewLine + currentLine.Trim();

                }
                sw.WriteLine(currentLine.Trim());
            }
            sw.WriteLine(@"END TRY
                                        BEGIN CATCH
                                        SELECT @er+=','+LTRIM(RTRIM(STR(ERROR_LINE())))
                                    END CATCH SELECT @er AS errorLines,@i AS errorCount");
            sw.Close();
            sr.Close();

        }
    }
    #endregion
    ExecuteConvertedFile(ResultPath,Server.MapPath(@"~/Data/Uploads/csv/ErrorLogs/ErrorLog.sql"));
}

void ExecuteConvertedFile(string ResultPath, string errorResultPath)
{
    string wholeQuery = System.IO.File.ReadAllText(ResultPath);
    using (SqlCommand cmd = new SqlCommand { CommandType = CommandType.Text, CommandText = wholeQuery, Connection = new SqlConnection(((SqlConnection)((EntityConnection)new NezaratEntities().Connection).StoreConnection).ConnectionString) })
    {
        cmd.Connection.Open();
        var dr = cmd.ExecuteReader();
        dr.Read();

        WriteErrorLogs(ResultPath,errorResultPath,dr["errorLines"].ToString().Trim());
        Label1.Text = dr["errorCount"].ToString()+"unsuccessful transactions";

    }
}

保存不成功的sql命令:

void WriteErrorLogs(string sourcePath, string ResultPath,string errorLinesTolog)
{
    string[] lines = File.ReadAllLines(sourcePath);
    string ErrorLog="";
    errorLinesTolog=errorLinesTolog.Remove(0, 1);

    foreach (var line in errorLinesTolog.Split(','))
    {
        ErrorLog += lines[int.Parse(line)-1] + Environment.NewLine;
    }
    System.IO.File.WriteAllText(ResultPath, ErrorLog);
}