SQL Wrapped in a Transaction

Nothing wakes you up faster in the morning than a cup of coffee or running a SQL Update without a Where clause.

One thing I’ve gotten in the habit of using is a simple script to update or delete SQL data. It’s kept me out of trouble more often than not.

  1. Select with the where clause.
  2. Perform the update (with the same where clause).
  3. Only commit the transaction if the expected number of rows are updated.
  4. Select again to visually compare the results.
select col, * 
from table
where 

BEGIN TRANSACTION T1
DECLARE @rc int

     update
     set
        where

SET @rc = @@ROWCOUNT
IF @rc <> 
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION

select col, * 
from table
where

Leave a Reply