1

I am trying to code a method where a user can pass multiple sql statements in string array format. and create a transaction. Rollback if nessesary. At the moment I get an error saying that the transaction needs a command to execute. Any advice would be appreciated, Maybe another(or right) way of doing what I need done. The following is the existing code.

public bool Scalar(params string[] sqlTexts)
{
    SqlTransaction tran = null;

    try
    {
        using (SqlConnection connection = new SqlConnection(strConnectionString)) // Auto dispose of connection
        {
            connection.Open(); // Open the connection
            using (tran = connection.BeginTransaction())
            {
                using (SqlCommand cmdCommand = connection.CreateCommand()) // Auto dispose of command
                {
                    foreach (string currentSQL in sqlTexts)
                    {
                        cmdCommand.CommandText = currentSQL;
                        cmdCommand.ExecuteScalar();
                    }
                }

                tran.Commit();
            }
        }
        return true;
    }
    catch (Exception)
    {
        if (tran != null)
            tran.Rollback();
        return false;
    }
}
1
  • When you debug does currentSQL hold a valid SQL statement with each iteration of the for loop? Might be a good idea to set the CommandType depending on the command to be executed. Commented Jul 22, 2013 at 9:07

1 Answer 1

4

You need to pass the transaction to the command before executing it:

cmdCommand.Transaction = tran;

Furthermore, you might want to be careful. You're using the transaction tran in the try block, but referencing it afterwards in the catch block. I would suggest moving the try/catch to inside the using(tran=...) block.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, Yes but its declared outside the try catch block :) Thanks so much for the advice though. It worked.
Yes but it will be disposed before you hit the catch block, so I believe tran.Rollback() will throw an exception and not work
Any ideal why it would end up executing all the sql statements twice?
@ReidGarwin Not from the code presented. Trace through the program and see exactly what's getting called when
Turns out that the ExecuteScalar was the cause. ExecuteNonQuery worked perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.