8

I'm working on a Python script that writes records from a stored procedure to a text file. I'm having issues executing the stored procedure with parameters.

I'm not sure what I could do differently to execute this stored procedure with both parameters. You can see the error I'm getting below.

Any insight would be appreciated.

Here's my code

# Import Python ODBC module
import pyodbc

# Create connection
cnxn = pyodbc.connect(driver="{SQL Server}",server="<server>",database="<database>",uid="<username>",pwd="<password>")
cursor = cnxn.cursor()

# Execute stored procedure
storedProc = "exec database..stored_procedure('param1', 'param2')"

# Loop through records
for irow in cursor.execute(storedProc):

    # Create a new text file for each ID
    myfile = open('c:/Path/file_' + str(irow[0]) + '_' + irow[1] + '.txt', 'w')

    # Write retrieved records to text file
    myfile.write(irow[2])

    # Close the file
    myfile.close()

Here's the error

Traceback (most recent call lst):
File "C:\Path\script.py", line 12, in <module>
  for irow in cursor.execute(storedProc):
      pyodbc.ProgrammingError: ('42000', "[4200] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'param1'. <102> <SQLExecDirectW>">

3 Answers 3

5

I was able to fix the syntax error by removing the parenthesis from the query string.

# Execute stored procedure
storedProc = "exec database..stored_procedure('param1', 'param2')"

should be

# Execute stored procedure
storedProc = "exec database..stored_procedure 'param1','param2'"
Sign up to request clarification or add additional context in comments.

Comments

2

This worked for me

query = "EXEC [store_proc_name] @param1='param1', @param2= 'param2'"
cursor.execute(query)

Comments

1

For SQL Server:

cursor.execute('{call your_sp (?)}',var_name)

Comments

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.