Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing an Integer in SQL Server

Tags:

sql

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?

like image 519
Ana Betts Avatar asked Dec 04 '09 23:12

Ana Betts


2 Answers

You don't need the inner select:

UPDATE TheTable SET RevisionId = RevisionId + 1 WHERE Id=@id
like image 63
Mark Byers Avatar answered Sep 22 '22 12:09

Mark Byers


This is a SQL idiom for incrementing a field:

UPDATE TheTable
 SET RevisionId = RevisionId + 1
 WHERE Id=@id;
like image 30
wallyk Avatar answered Sep 22 '22 12:09

wallyk