I have a windows forms application that executes some sql scripts in a database at the click of a button.These sql scripts do user creation, and giving some permissions like data execute, data read/write etc.. Here is my sample c# code for doing this:
script1 = "CREATE USER " + username + " FROM LOGIN " + username;
script2 = @"CREATE ROLE [db_execute] AUTHORIZATION [dbo]
GRANT EXECUTE TO [db_execute]";
script3 = @"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";
And executing this in the database like:
SqlCmd.CommandText = script1;
SqlCmd.Connection = oConnection;
var ans = SqlCmd.ExecuteNonQuery();
if (!ans.Equals(0))
{
//some task
} else
{
//messagebox
}
SqlCmd.CommandText = script2;
SqlCmd.Connection = oConnection;
var answer = SqlCmd.ExecuteNonQuery();
if (!answer.Equals(0))
{
//some task
} else
{
//messagebox
}
SqlCmd.CommandText = script3;
SqlCmd.Connection = oConnection;
var answ = SqlCmd.ExecuteNonQuery();
if (!answ.Equals(0))
{
//some task
} else
{
//messagebox
}
I am executing all these scripts at a time by the press of a button,so in my understanding I am doing this as a single transaction. What I want to do is that, if in case any of these scripts fail in between I should be able to rollback fully without doing any change.
For giving you a better picture,if in case the execution of script3 got failed for some reason, it should automatically rollback whatever the script1 and script2 done in the database.
How can we do this? I googled it and found some irrelevant posts for this.
Any help or ideas would be really appreciated..