HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

CLR/C# equivalent to XACT_STATE()

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
clrequivalentxact_state

Problem

I am porting a set of T-SQL stored procedures to C#/CLR. In the T-SQL, we use XACT_STATE() to determine if an error requires rolling back to a savepoint or rolling back the transaction entirely.

I cannot find an equivalent check of the transaction using the System.Data.SqlClient.SqlTransaction or System.Transactions.TransactionScope objects.

Does anyone know how to check the transaction state from within C#/CLR?

Solution

XACT_STATE() is not something that SqlClient has any special insight on, much like transaction level. So, just query it with SqlCommand.

// If you already have an open connection...
public int GetXactState (SqlConnection connection)
{   
    using (SqlCommand command = new SqlCommand("Select XACT_STATE();", connection)) {
        return (int)command.ExecuteScalar();
    }
}

Code Snippets

// If you already have an open connection...
public int GetXactState (SqlConnection connection)
{   
    using (SqlCommand command = new SqlCommand("Select XACT_STATE();", connection)) {
        return (int)command.ExecuteScalar();
    }
}

Context

StackExchange Database Administrators Q#106368, answer score: 3

Revisions (0)

No revisions yet.