A
Andy B.
I created the following stored procedure. It inserts a row into the
Headlines table. If it fails, it returns -1 with the error that sql server
returned. So far, everything seems to be working right except the rollback
part. Is there any reason why the rollback fails?
Headlines table. If it fails, it returns -1 with the error that sql server
returned. So far, everything seems to be working right except the rollback
part. Is there any reason why the rollback fails?
Code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Transactions;
public partial class StoredProcedures {
[Microsoft.SqlServer.Server.SqlProcedure]
public static void InsertHeadline(string Title, string Description, string
Content, DateTime StartDate, DateTime EndDate) {
string SqlQuery = "INSERT INTO Headlines (HeadlineTitle,
HeadlineDescription, HeadlineContent, HeadlineStartDate, HeadlineEndDate)
values (@HeadlineTitle, @HeadlineDescription, @HeadlineContent,
@HeadlineStartDate, @HeadlineEndDate)";
try {
using(TransactionScope Scope = new TransactionScope()) {
using(SqlConnection Connection = new SqlConnection("context
connection=true")){
SqlCommand Command = new SqlCommand(SqlQuery, Connection);
#region Command parameters
Command.Parameters.Add("@HeadlineTitle", DbType.String);
Command.Parameters["@HeadlineTitle"].Value = Title;
Command.Parameters.Add("@HeadlineDescription", DbType.String);
Command.Parameters["@HeadlineDescription"].Value = Description;
Command.Parameters.Add("@HeadlineContent", DbType.String);
Command.Parameters["@HeadlineContent"].Value = Content;
Command.Parameters.Add("@HeadlineStartDate", DbType.Date);
Command.Parameters["@HeadlineStartDate"].Value = StartDate;
Command.Parameters.Add("@HeadlineEndDate", DbType.Date);
Command.Parameters["@HeadlineEndDate"].Value = EndDate;
#endregion
Connection.Open();
Command.ExecuteNonQuery();
} //end connection.
Scope.Complete();
} //end transaction.
} catch(Exception ex) {
using(SqlConnection Connection = new SqlConnection("context
connection=true")) {
Connection.Open();
SqlCommand Command = new SqlCommand("SELECT -1, @ErrorMessage", Connection);
Command.Parameters.Add("@ErrorMessage", DbType.String);
Command.Parameters["@ErrorMessage"].Value = ex.Message;
SqlContext.Pipe.ExecuteAndSend(Command);
}
}
}
};