Is there a way, using a trigger or some other means, to ensure that a particular field is always explicitly set when a row is updated, even when running ad hoc SQL via SQL Server Management Studio? Specifically, our tables all have change_note fields, and we always want that field to be set for every update. Things we’ve considered and discarded:
-
Set change_note to NOT NULL. We do this, but it doesn’t help. Once change_note has an initial value, you can run as many UPDATE statements as you want that forget to update change_note and NOT NULL remains happy because the previous value is still sitting in change_note.
-
Use a trigger to compare the old version of change_note to the new value of change_note. Sometimes you want change_note to be the same as it was previously. It’s not that we want to ensure that change_note changes, we want to ensure that a value for it is explicitly provided in any update.
-
Deny permissions for running ad hoc SQL and force everybody to only update data through our stored procedure API, and make change_note a required param for all SPs that update the relevant tables. We have too many ad hoc querying needs for this.
Stumped! Any ideas?
Thanks!
You can use the Update() function within the trigger body. It will check if the statement which fired the trigger tried to change the value on the column:
You can find more information about it in:
http://msdn.microsoft.com/en-us/library/ms187326.aspx
http://msdn.microsoft.com/en-us/library/aa258254(v=sql.80).aspx