Search code examples
pythonsql-serverpython-2.7stored-procedurespypyodbc

"(u'24000', u'[24000] [Microsoft][ODBC SQL Server Driver]Invalid Cursor State)" in python pypyodbc


I want to execute the procedure and get the output parameters

import pypyodbc

command = "DECLARE @l_Stat INT \r\n" \
                  "DECLARE @s_Ms VARCHAR(200) \r\n" \
                  "EXEC p_Log_InsertParam_2011v1 " \
                  "@l_TesterId=?, " \
                  "@l_ObiektId=?, " \
                  "@l_RejPId=?, " \
                  "@s_ParamName=?, " \
                  "@f_ParamValue=?, " \
                  "@f_ParamMinValue=?, " \
                  "@f_ParamMaxValue=?, " \
                  "@b_CheckParam=?, " \
                  "@l_Status=@l_Stat output, " \
                  "@s_Msg=@s_Ms output \r\n" \
                  "SELECT @l_Stat, @s_Ms\r\n"
connection = pypyodbc.connect(self.ConnectionString)
cursor = connection.cursor()
params=(453879185, 23192812, 645872, '/APL/CTRL_GZ/PID/SP', 35.0, 0, 0, True)
# params = (testerid,
#          obiektid,
#          rejpid,
#          paramname,
#          paramvalue,
#          paramminvalue,
#          parammaxvalue,
#          checkparam) """
result = cursor.execute(command, params)
pars = result.fetchall()[0]
print pars
if pars.__len__() >= 2:
    l_status = pars[0]
    s_msg = pars[1]
print "{}: {};".format(l_status, s_msg)

It runs well to the line result = cursor.execute(command, params) - procedure execute properly. Problem appears when I try to fetch the result in line pars = result.fetchall()[0]:

u'24000', u'[24000] [Microsoft][ODBC SQL Server Driver]Invalid Cursor State'

How can I get rid of this error?


Solution

  • I was able to reproduce your issue when my p_Log_InsertParam_2011v1 stored procedure did not have

    SET NOCOUNT ON;
    

    as its first executable statement. When I added it at the beginning of my stored procedure the error went away.