This is not a repeated question of rollback sql transactions if any failed in c#. 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.
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..