开发者

SQL Server instead of insert triggers - is there an easy way to modify a single column?

Given that SQL Server does not allow modification of the logical INSERTED and DELETED tables in a trigger, is there an easy way to change the value of a single column and not have to re-write the entire insert statement?

For example, the table to which I am applying the trigger has 20 columns. I want to modify the value from the INSERTED table for one column开发者_如何学运维 (per row) and then insert that row into the table. Can I do so without writing an insert statement with 19 columns plus the one column whose value I'm modifying?


Yes, just use an "after insert" trigger, instead of a "instead-of insert" trigger.

That way the row has already been inserted into the table, and all you have to do is issue a (carefully crafted) update statement, usually by inner-joining to the INSERTED table on the primary key field.


To add more detail to BradCs answer:

The syntax for an update with a join is a little wonky

Update table
  set columnA = inserted.columnA / 10
from table
inner join inserted on table.id = inserted.id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜