C# 中 SQL 脚本的执行流程

本文关键字:执行流 脚本 SQL | 更新日期: 2023-09-27 18:32:38

这不是一个

重复的问题,如果 c# 中有任何失败,回滚 sql 事务。但这个问题是基于上一个问题的内容。感谢所有对我的最后一个问题发表意见的人。我尝试了所有这些解决方案,最终发现我在应用程序(DDL(中使用的脚本不允许在多语句事务中使用。

我的整个代码是这样的:

script1 = "CREATE USER " + username + " FROM LOGIN " + username;
script2 = "CREATE ROLE " + rolename;
script3 = @"CREATE ROLE [db_execute] AUTHORIZATION [dbo]
                        GRANT EXECUTE TO [db_execute]";
script4 = @"DECLARE @rolename varchar(max)
                    SET @rolename ='{0}'
                    EXEC sp_addrolemember N'db_execute',@rolename
                    EXEC sp_addrolemember N'db_datareader', @rolename
                    EXEC sp_addrolemember N'db_datawriter', @rolename";
script_result = string.Format(script4, rolename);
script6 = "EXEC sp_addrolemember '{0}', '{1}'";
            outp = string.Format(script6, rolename, username);
script7 = @"select m.name as Member, r.name as Role
                    from sys.database_role_members
                    inner join sys.database_principals m on sys.database_role_members.member_principal_id = m.principal_id
                    inner join sys.database_principals r on sys.database_role_members.role_principal_id = r.principal_id";

并以如下所示的相同方式执行所有这些:

SqlCommand SqlCmd = new SqlCommand();
//Create User Script Execution
SqlCmd.CommandText = script1;
SqlCmd.Connection = oConnection;        
lvinfo.Items.Add("Executing Create User script in " + dbname + " database");
var answer = SqlCmd.ExecuteNonQuery();
//Checking whether execution completed successfully
if (!answer.Equals(0))
{
lvinfo.Items.Add("Create User script executed successfully in " + dbname + " database");                                                                          
}
else
{
lvinfo.Items.Add("Create User script execution failed in " + db_select.SelectedItem.ToString() + " database");
}

尽管我只编写了这段代码,但现在我对这些脚本的执行有些怀疑。上面显示的所有脚本一次执行,只需单击一个按钮。我想知道的是,这些脚本会一次完全执行吗?意味着,一次执行这些脚本时是否有可能执行失败?以数据库断开连接或任何其他错误的形式出现的机会。

让我向您展示我所问的一个例子:如果前 3 个脚本以某种方式被执行,而所有其他脚本都失败了,那么是否有机会自动回滚?

或者我的代码是否在整个代码执行之前检查是否有任何错误或失败机会,以便它永远不需要回滚?

任何人都可以支持我提供宝贵的建议和想法。

任何帮助将不胜感激。

C# 中 SQL 脚本的执行流程

我已经给出了一个骨架,说明它可能是什么样子。你可以告诉我你想要回滚什么和什么不是场景。

var scriptToExecute = new Dictionary<int, string>();
            var scriptToRollback = new Dictionary<int, string>();
        try
        {
            using (SqlCommand SqlCmd = new SqlCommand())
            {
                //Create User Script Execution
                SqlCmd.CommandText = script1;
                SqlCmd.Connection = oConnection;
                lvinfo.Items.Add("Executing Create User script in " + dbname + " database");
                var answer = SqlCmd.ExecuteNonQuery();
                //Checking whether execution completed successfully
                if (!answer.Equals(0))
                {
                    lvinfo.Items.Add("Create User script executed successfully in " + dbname + " database");
                }
                else
                {
                    lvinfo.Items.Add("Create User script execution failed in " + db_select.SelectedItem.ToString() + " database");
                }
            }
        }
        catch (SqlException)
        {
            string rollbackScript = string.Empty;
            for (int i = scriptExecuting; i > 0; i--)
            {
                scriptToRollback.TryGetValue(i, rollbackScript);
                if (!string.IsEmpty(rollbackScript))
                {
                    //Execute the scripts here.
                }
            }
        }

        finally
        {
            //If connection is open then close the active connection
        }