23

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?

3 Answers 3

51

You don't need the inner select:

UPDATE TheTable SET RevisionId = RevisionId + 1 WHERE Id=@id 
Sign up to request clarification or add additional context in comments.

Comments

15

This is a SQL idiom for incrementing a field:

UPDATE TheTable SET RevisionId = RevisionId + 1 WHERE Id=@id; 

2 Comments

Make sure you do it in a transaction or you'll end up trying to chase down the weirdest bugs.
@Donnie: what are you talking about? UPDATE ... SET field = field + 1 is always atomic.
1

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.

2 Comments

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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.