简体   繁体   中英

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.

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)

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM