How to debug "Invalid transaction state" error in ODBC?

Igor Korot 26 Reputation points
2025-01-18T19:19:58.4133333+00:00

Hi, ALL,

I have an application that throws an aforementioned error upon exit/disconnect.

I know that every transaction I start I COMMIT/ROLLBACK and those transactions are doing "CREATE TABLE/INSERT" statements.

However I am also doing SELECT statements outside of explicit BEGIN {TRANSACTION} statement.

Unfortunately the doc at https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqldisconnect-function?view=sql-server-ver16 does not help with identifying what and where the error is coming from.

My question now is: do I have to COMMIT/ROLLBACK every single SELECT, INSERT, DELETE and CREATE to fix that error?

Also, I'm calling:

ret = SQLSetConnectAttr( m_hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) FALSE, 0 );

in my application.

Please advise.

Thx.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,320 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,829 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Erland Sommarskog 115.6K Reputation points MVP
    2025-01-18T19:33:32.1+00:00

    If I understand this line correctly:

    ret = SQLSetConnectAttr( m_hdbc, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) FALSE, 0 );

    You are turning off auto-commit, or in SQL Server parlance, you are setting the option IMPLICIT_TRANSACTIONS ON. (The default for this setting is OFF.) When this setting is ON, any DML or DDL statement, including SELECT; starts a transaction, which must be explicitly committed and rolled back.

    This is a very odd creature in the SQL Server world, but it is actually standard, so this is the norm in many other products.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.