简体   繁体   English

C#中SQL脚本的执行流程

[英]Execution flow of SQL Script in c#

This is not a repeated question of rollback sql transactions if any failed in c# . 如果c#中有任何失败,这不是回滚sql事务的重复问题。 But this question is based on the content of the previous question. 但是这个问题是基于上一个问题的内容。 Thanks to all who gave their opinion on my last question.I tried all those solutions and could finally found out that the scripts which I use in my application(DDL) are not allowed within multi-statement transaction. 感谢所有对我的最后一个问题发表意见的人。我尝试了所有这些解决方案,最终发现在多语句事务中不允许在我的应用程序(DDL)中使用脚本。

My entire code is like this: 我的整个代码是这样的:

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";

and executing all these in the same way as shown below: 并以如下所示的相同方式执行所有这些操作:

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");
}

Even though I only wrote this code, now I am having some doubts on the execution of these scripts. 即使我只写了这段代码,现在我对这些脚本的执行还是有些怀疑。 All the scripts shown above are executed at a time, on the click of a button. 单击按钮,一次即可执行上面显示的所有脚本。 What I want to know is that will these scripts get executed at a time fully?Means, is there any chance for an execution failure while executing these scripts,at a time?Chance in the form of database disconnection, or any other errors. 我想知道的是,这些脚本会一次全部执行吗?意味着,一次执行这些脚本时是否有执行失败的可能?数据库断开或其他任何错误的机会。

Let me show you an example of what I am asking:If somehow the first 3 scripts got executed, and all the rest of the scripts failed, is there any chance for rollback automatically then? 让我向您展示一个我要问的示例:如果以某种方式执行了前三个脚本,而所有其他脚本都失败了,那么是否有自动回滚的机会?

Or do my code checks for any errors or failure chances before the entire code gets executed so that it need not have a rollback ever? 还是我的代码在执行整个代码之前检查是否有任何错误或失败的机会,这样就不需要回滚了?

Can anyone please support me with their valuable suggestions and ideas.. 任何人都可以通过他们的宝贵建议和想法来支持我。

Any help would be really appreciated.. 任何帮助将非常感激..

I have given a skeleton for what it may look like. 我已经给出了大概的样子的骨架。 You can tell me what all you want to rollback on what and what not scenarios. 您可以告诉我您想在什么情况下回滚什么,而不是什么情况。

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
        }

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

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