1

HI i am trying to update a table in sql server using pyodbc but i am not able to get the correct syntax. Code snippet-

def fun(cur,tablename):

    cur.execute("""UPDATE sam
        SET
        sam.agreement_id = ?
        FROM '{0}' sam
        INNER JOIN dbo.agreement_mapping am ON sam.agreement_id = ?;
        """.format(tablename.replace('\'', '\'\'')),am.newagreementid,am.oldagreementid)

I am getting the error `"name 'am' is not defined". Is there any way i can perform this update query ?

2
  • The values for the placeholders need to be in a tuple or list: (am.newagreementid,am.oldagreementid) Commented Feb 10, 2018 at 21:52
  • @Barmar - Actually, that's not strictly true for pyodbc. As explained here, crsr.execute(stmt, paramval1, paramval2) is supported. Commented Feb 10, 2018 at 23:42

1 Answer 1

1

Refactoring your code for clarity,

def fun(cur,tablename):

    cur.execute("""UPDATE sam
        SET
        sam.agreement_id = ?
        FROM '{0}' sam
        INNER JOIN dbo.agreement_mapping am ON sam.agreement_id = ?;
        """.format(tablename.replace('\'', '\'\'')),am.newagreementid,am.oldagreementid)

becomes

def fun(cur,tablename):
    stmt = """\
        UPDATE sam
        SET
        sam.agreement_id = ?
        FROM '{0}' sam
        INNER JOIN dbo.agreement_mapping am ON sam.agreement_id = ?;
        """.format(tablename.replace('\'', '\'\''))
    cur.execute(stmt, am.newagreementid, am.oldagreementid)

There are two problems:

First, '{0}' wraps the table name in single quotes, turning it into a string literal. SQL Server table names are delimited by square brackets.

Second, the am.newagreementid and am.oldagreementid references in the execute call are evaluated in Python. Your Python code does not declare any Python variable or object named am, so those references are invalid.

So instead, you need to do something like this:

def fun(cur,tablename):
    stmt = """\
        UPDATE sam
        SET
        sam.agreement_id = am.newagreementid
        FROM [{0}] sam
        INNER JOIN dbo.agreement_mapping am ON sam.agreement_id = am.oldagreementid;
        """.format(tablename.replace('\'', '\'\''))
    cur.execute(stmt)
Sign up to request clarification or add additional context in comments.

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.