tags:

views:

112

answers:

3

Noob question here, every time I change a certain record in an SQL Server 2008 R2 table, I want to increment a RevisionId record; to do so, I'm using the following syntax:

UPDATE TheTable SET RevisionId=(SELECT RevisionId FROM TheTable WHERE Id=@id)+1 WHERE Id=@id;

Btw, I'm going to put this into a trigger so that this happens automagically, but while this code works, it feels pretty clunky - any cleaner way to do this?

+6  A: 

This is a SQL idiom for incrementing a field:

UPDATE TheTable
 SET RevisionId = RevisionId + 1
 WHERE Id=@id;
wallyk
Make sure you do it in a transaction or you'll end up trying to chase down the weirdest bugs.
Donnie
@Donnie: what are you talking about? UPDATE ... SET field = field + 1 is always atomic.
Remus Rusanu
+10  A: 

You don't need the inner select:

UPDATE TheTable SET RevisionId = RevisionId + 1 WHERE Id=@id
Mark Byers
+1  A: 

If you're just looking for a "row version" value, have you considered adding a TimeStamp column to your table? SQL Server updates it for you "automagically" every time. No code on your part at all. They just won't be sequentially numbered, if that's important to you.

No Refunds No Returns
That's interesting as well, thanks for the tip! In this case though, I want to update the row's container as well (I have a treeish structure in the table), but using a time instead of a revision might be a good idea too
Paul Betts
SQL Server's "timestamp" is a 64-bit sequential integer for your data base. It's too bad it's called timestamp because it has absolutely nothing to do with dates or times. It's designed for use by replication processes.
No Refunds No Returns