user1238784
user1238784

Reputation: 2440

MSSqlServer error:the transaction is completed

I get error trying to work with transactions. Without it everything runs fine, but with it I get a strange error: the transaction is completed and cannot be utilized anymore (my translation of the error)

Here is my code till the error:

using (var conn = new SqlConnection(gl.constr))
{
    using (SqlCommand cm = new SqlCommand())
    {
        conn.Open();
        using (SqlTransaction tr = conn.BeginTransaction())
        {
            try
            {
                cm.Connection = conn;
                cm.Transaction = tr;
                cm.CommandText = "INSERT INTO Bookings (Time, Price, BookingRef, BookingInternalRef)" +
                                  " VALUES(" +
                                  "getdate(), "+ sPrice + ", " + 
                                  db.AddAphens(reference) + ", " +
                                  db.AddAphens(internalBookref) +
                                  ")";
                cm.ExecuteNonQuery();  //this works
                tr.Commit();

On the commit the error popups.

Upvotes: 0

Views: 86

Answers (1)

Rahul
Rahul

Reputation: 77936

You don't need a explicit transaction declaration SqlTransaction tr = conn.BeginTransaction() for a single DML operation since every DML operation will be implicit transaction bound. Thus you can remove your transaction declaration all-together and it should work fine

Upvotes: 1

Related Questions