简体   繁体   中英

Auto Increment Column value whenever update happen on that row in sql server

I want to maintain a column which will store that how many times a row has been modified. So whenever the row has been updated I want to increase the column value. I think I have to use trigger for that.But I am looking for an alternative solution.

IMHO trigger is the way to go, but if you sure that you control all your updates, then you can do as simple as this:

UPDATE mytable 
   SET somefield='newvalue', 
       update_count = update_count+1 
   WHERE id=n
CREATE TRIGGER CountRows 
    ON TestCount 
    after Update
AS 
Update TestCount  set Cnt = Cnt +1 where ID in (select ID from inserted)
GO

whenever some value in a row changes, the grigger adds +1 to the same row's Cnt column value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM