1

I have been following the documentation on the pyodbc page on PyPi and I can't seem to get the code to work. https://github.com/mkleehammer/pyodbc/wiki/Calling-Stored-Procedures

Using Python 3.8.10

conn = pyodbc.connect(connString)
cursor = conn.cursor()
startSQL = '''
    DECLARE @load_id INT;
    EXEC dbo.ETL_StartLoad @JobName = 'test',  @LoadID = @load_id output;
    SELECT @load_id AS Load_ID;
'''
print(startSQL)
cursor.execute(startSQL)
auditList = cursor.fetchall()
print(auditList)

When I run the code it fails with the following error:

auditList = cursor.fetchall()
pyodbc.ProgrammingError: No results.  Previous SQL was not a query.

If I copy and paste the SQL in SSMS and run it then it works just fine.

3
  • I think you need to start with """\ Commented Jan 3, 2023 at 23:14
  • 1
    See the updated wiki page. TL;DR - You need to put SET NOCOUNT ON; at the beginning of your anynymous code block. Commented Jan 4, 2023 at 16:05
  • @GordThompson this worked. Please answer the question so i can give you credit for it. Commented Jan 5, 2023 at 21:58

1 Answer 1

1

The most common cause of

pyodbc.ProgrammingError: No results. Previous SQL was not a query.

when executing a stored procedure is that the procedure itself does not include SET NOCOUNT ON;and it performs DML actions (INSERT, UPDATE, DELETE) that return a rowcount. To avoid the error, include SET NOCOUNT ON; at the beginning of the anonymous code block, e.g.,

startSQL = '''\
    SET NOCOUNT ON;
    DECLARE @load_id INT;
    EXEC dbo.ETL_StartLoad @JobName = 'test',  @LoadID = @load_id output;
    SELECT @load_id AS Load_ID;
'''
Sign up to request clarification or add additional context in comments.

3 Comments

The transaction returns the correct value to the command prompt but in the database the transaction is getting rolled back. So the value doesnt exists in the DB anymore when I query it directly. Any Python specific reason for this?
Are you calling conn.commit() to commit the changes?
Since the code inside the sproc is wrapped in a transaction I didnt think I needed to commit the sproc code again in the python code. Adding the conn.commit() works. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.