Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server return value with pyodbc

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.

like image 547
ChangeMyName Avatar asked May 05 '15 16:05

ChangeMyName


2 Answers

Trying to run multi-statement T-SQL scripts via pyodbc can be problematic. Even though this works fine in SSMS

DECLARE @tbl AS TABLE (retVal INT);
INSERT INTO @tbl (retVal) 
        EXEC [dbo].proc_mySP
                @group = 37,
                @description = 'foo';
SELECT retVal FROM @tbl;

the following Python code ...

sql = """\
DECLARE @tbl AS TABLE (retVal INT);
INSERT INTO @tbl (retVal) 
        EXEC [dbo].proc_mySP
                @group = 37,
                @description = ?;
SELECT retVal FROM @tbl;
"""
crsr.execute(sql, ['foo'])
row = crsr.fetchone()

... fails with

pyodbc.ProgrammingError: No results. Previous SQL was not a query.

If the stored procedure returns a single-row result set with a single column then all you need to do is

import pyodbc
cnxn = pyodbc.connect("DSN=myDb_SQLEXPRESS")
crsr = cnxn.cursor()
sql = """\
EXEC [dbo].proc_mySP
        @group = 37,
        @description = ?;
"""
crsr.execute(sql, ['foo'])
the_result = crsr.fetchone()[0]
print(the_result)
like image 103
Gord Thompson Avatar answered Oct 18 '22 14:10

Gord Thompson


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.

conn = pyodbc.connect("driver={SQL Server};server=MyServer;database=MyDB;trusted_connection=true") 

cursor = conn.cursor()

SQL_command = """
                SET NOCOUNT ON;
                DECLARE @ret INT

                EXEC @ret = [dbo].proc_mySP             
                  @group= 0
                , @description =?

                SELECT @ret
              """

cursor.execute(SQL_command, description)
retValue = cursor.fetchall()
like image 27
Lucas925 Avatar answered Oct 18 '22 16:10

Lucas925