MSSQL2008 - Pyodbc - Previous SQL was not a query MSSQL2008 - Pyodbc - Previous SQL was not a query python python

MSSQL2008 - Pyodbc - Previous SQL was not a query


Just in case some lonely net nomad comes across this issue, the solution by Torxed didn't work for me. But the following worked for me.

I was calling an SP which inserts some values into a table and then returns some data back. Just add the following to the SP :

SET NOCOUNT ON

It'll work just fine :)

The Python code :

    query = "exec dbo.get_process_id " + str(provider_id) + ", 0"    cursor.execute(query)    row = cursor.fetchone()    process_id = row[0]

The SP :

USE [DBNAME]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER procedure [dbo].[GET_PROCESS_ID](    @PROVIDER_ID INT,    @PROCESS_ID INT OUTPUT)ASBEGIN    SET NOCOUNT ON    INSERT INTO processes(provider_id) values(@PROVIDER_ID)    SET @PROCESS_ID= SCOPE_IDENTITY()    SELECT @PROCESS_ID AS PROCESS_IDEND


Using the "SET NOCOUNT ON" value at the top of the script will not always be sufficient to solve the problem.

In my case, it was also necessary to remove this line:

Use DatabaseName;

Database was SQL Server 2012,Python 3.7,SQL Alchemy 1.3.8

Hope this helps somebody.


I got this because I was reusing a cursor that I was looping over:

rows = cursor.execute(...)for row in rows:    # run query that returns nothing    cursor.execute(...)    # next iteration of this loop will throw 'Previous SQL' error when it tries to fetch next row because we re-used the cursor with a query that returned nothing

Use 2 different cursors instead

rows = cursor1.execute(...)for row in rows:    cursor2.execute(...)

or get all results of the first cursor before using it again:

Use 2 different cursors instead

rows = cursor.execute(...)for row in list(rows):    cursor.execute(...)