SQL Server – Prevent Running UPDATE Without WHERE Clause

sql serverssms

Whenever I have to run an update statement, I always get nervous that I might forget the WHERE clause and overwrite the entire column in the database. Is there any setting or plugin or addon I can get for SQL Server Management Studio to block certain dangerous statements, unless you explicitly say its ok to run?

I'm working on a development server, so I can always roll back the changes, but still, I feel like I might have only the first two lines highlighted and click Execute or do something else stupid.

Best Answer

Create a trigger on update (another on delete is probably a good idea).

CREATE TRIGGER [Table].[uPreventUpdateOops] 
ON [Table]
FOR UPDATE AS 
BEGIN
     DECLARE @Count int
     SET @Count = @@ROWCOUNT;

     IF @Count >= (SELECT SUM(row_count)
         FROM sys.dm_db_partition_stats 
         WHERE OBJECT_ID = OBJECT_ID('Table') 
         AND index_id = 1)
     BEGIN
         RAISERROR('Cannot update all rows',16,1) 
         ROLLBACK TRANSACTION
         RETURN;
     END
END
GO

Note: This only prevents the most obvious mistake. Please do not use this on a production server as you're bound to find a statement that will totally Bork your table but pass this simple test. Also, this runs quite slow on large tables, performance will be affected.