Update fails after repeating deadlocked query in p

2019-05-22 20:25发布

问题:

I'm using SQL Server with pymssql, and found that a particularly complicated SELECT query would occasionally be selected as a deadlock victim. So I wrapped it in a while loop to retry the transaction if that happens, roughly as follows:

while True:

    try:

        cursor.execute('SELECT .......')
        count_row = cursor.fetchone();
        break

    except Exception, tec:

        print "Got error: %s" % (tec)
        time.sleep(1)

cursor.execute('UPDATE .........')
self.conn.commit()

It seems to work - if the SELECT hits a deadlock then it will pause for a second, retry again and get the right answer. However every time that occurs the following UPDATE statement always fails with:

pymssql.OperationalError: Cannot commit transaction: (3902, 'The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.DB-Lib error message 3902, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')

The UPDATE statement isn't in the while loop, so I have no idea why it's failing. It works fine when the SELECT doesn't hit the deadlock condition, so I think it's something to do with recovering from that error.

Any ideas?