HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Can SQL Server stop me from running an UPDATE statement without a WHERE clause?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
canwithoutupdatestatementsqlwherestoprunningserverfrom

Problem

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.

Solution

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.

Code Snippets

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

Context

StackExchange Database Administrators Q#72399, answer score: 4

Revisions (0)

No revisions yet.