Suppose that I have a table my_table(id, x, y). I want to write a trigger to prevent updating the y col and setting it to a non-null value if x is already null. As SQL Server doesn’t have a before update trigger, how can this be done? Apparently we can use an instead of trigger for this purpose, but how can we check the old and current values and decide whether we should raise an error or let the update execute normally?
Example:
Let’s pretend we have this row in the DB:
1, null, null
Then this should fail (raise error)
update my_table set y = 'blah' where id = 1;
But this should succeed:
update my_table set y = null where id = 1;
I know the example isn’t very meaningful, but it is similar to what I am trying to achieve.
This should work, but I am not sure what other edge conditions you need to handle: