How to test an SQL Update statement before running it?

前端 未结 9 1240
野趣味
野趣味 2020-12-23 20:29

In some cases, running an UPDATE statement in production can save the day. However a borked update can be worse than the initial problem.

Short of using a test datab

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 20:42

    In these cases that you want to test, it's a good idea to focus on only current column values and soon-to-be-updated column values.

    Please take a look at the following code that I've written to update WHMCS prices:

    # UPDATE tblinvoiceitems AS ii
    
    SELECT                        ###  JUST
        ii.amount AS old_value,   ###  FOR
        h.amount AS new_value     ###  TESTING
    FROM tblinvoiceitems AS ii    ###  PURPOSES.
    
    JOIN tblhosting AS h ON ii.relid = h.id
    JOIN tblinvoices AS i ON ii.invoiceid = i.id
    
    WHERE ii.amount <> h.amount   ### Show only updatable rows
    
    # SET ii.amount = h.amount
    

    This way we clearly compare already existing values versus new values.

提交回复
热议问题