sql server return value with pyodbc

一世执手 提交于 2019-12-24 03:50:12

问题


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.


回答1:


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)



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/30058957/sql-server-return-value-with-pyodbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!