views:

81

answers:

1

My requirement is to create temp table then exec a store procedure which will insert rows into the temp table then drop the temp table. However if there is an error when doing this, I want to always drop the temp table at the end. I know with enterprise libary managing connections, the table is dropped once the connection is closed anyway. However just want to see if it's possible to do this using Try and Finally block. Supporting both Sybase and MS Sql. So for e.g:

string preUploadSql = "create table #CHANGES ( Id numeric(18) identity not null)";
string postUploadSql = "drop table #CHANGES";
bCommand.CommandText = preUploadSql + "; " exec sp_update ;";

DbConnection dbConnection  = DataAccessHelper.CreateConnection();
if ( dbConnection.State != ConnectionState.Open )
{
    dbConnection.Open();
}
DbTransaction dbTransaction = dbConnection.BeginTransaction();

try
{
    DataAccessHelper.ExecuteNonQuery( dbCommand, dbTransaction );
}
finally
{
    dbCommand.CommandText = postUploadSql;
    DataAccessHelper.ExecuteNonQuery( dbCommand, dbTransaction );
    dbTransaction.Commit();
    if ( dbConnection.State == ConnectionState.Open )
    {
    dbConnection.Close();
    }
}

Is something like this possible ?, when I try this, if there is an error, the dbtransaction in final block doesn't seem to have access to the temp table which makes me think when there is an error, the transaction scope is out of context or something like that. Any ideas? How to best handle this?

+1  A: 

In order to get around this issue, what I did was use the connection and reuse that instead rather than use DBTransaction since Sybase (12 and 15) didn't seem to allow create table commands as part of the same transaction.

Rubans