sql server return value with pyodbc

2019-08-10 03:00发布

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.

3条回答
等我变得足够好
2楼-- · 2019-08-10 03:55

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)
查看更多
唯我独甜
3楼-- · 2019-08-10 03:57

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()
查看更多
闹够了就滚
4楼-- · 2019-08-10 03:57

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.

查看更多
登录 后发表回答