I want to define a column in my table with following requirements:
- The column should be insertable. If the value is provided in the INSERT statement, then it should be inserted.
- If the column is not referenced in the INSERT statement, then it should be set to the sum of two other columns.
Because of the first requirement, I cannot user computed columns, since they are not insertable. Because of the second, I cannot use DEFAULT, because it doesn’t allow referencing other columns in the definition. What other options do I have?
BTW, the column should be NOT NULL.
Here you go, I’m demonstrating this with an example schema since you’ve not provided your real table/column names.
Table:
Here is the trigger definition:
Basically it replaces any insert statement done on the table with the one in the trigger, so I check using the
insertedtemporary table to see if the value that is trying to be inserted into our non-nullable optional column,col3, is NULL. If it is, I replace it with the addition ofcol1andcol2(I’m coalescing with zero as you didn’t mention if the two source columns are nullable or not).You can then run insert statements which either include it or not, despite the fact
col3is not nullable:Results are:
If the trigger wasn’t there, you could have got an error trying to run that first insert statement, telling you it couldn’t insert NULL into
col3.Notice also that the second insert statement that specifies a value has not been replaced by the addition, as requested.
Here’s a working SQL Fiddle.