I am trying to run some stored proc with pyodbc
and get the single return value using following code:
conn = pyodbc.connect("driver={SQL Server};server=MyServer;database=MyDB;trusted_connection=true")
cursor = conn.cursor()
SQL_command = """
DECLARE @ret INT
EXEC @ret = [dbo].proc_mySP
@group= 0
, @description =?
SELECT @ret
"""
cursor.execute(SQL_command, description)
retValue = cursor.fetchall()
And the framework of the stored proc is as follows:
-- SOME CODE
-- ......
-- EXEC another_sp
-- DECLARE @RET INT
-- SELECT @RET as retValue
-- ......
The above sql works fine in sql server, however, when it was called by the above Python code, it gives error messages:
pyodbc.ProgrammingError: ('24000', '[24000] [Microsoft][ODBC SQL Server Driver]Invalid cursor state (0) (SQLNumResultCols)')
May I know what is wrong with my code?
Many thanks.
Trying to run multi-statement T-SQL scripts via pyodbc can be problematic. Even though this works fine in SSMS
the following Python code ...
... fails with
If the stored procedure returns a single-row result set with a single column then all you need to do is
I have this error in my own code by adding SET NOCOUNT ON; as the first line of your SQL that you are passing from Python.
Just add "SET NOCOUNT ON;" as the first line in a procedure and pyodbc will be able to get the data from a select statement at the end of the procedure.