JaggenSWE
JaggenSWE

Reputation: 2094

SELECT a cell and UPDATE at the same time?

I've got a SQL Server table in which I have a column where I would like to select the current value and increment by one, is there a way to do this in a single query? This in order to mitigate the chance, however small it might be, that someone else gets the same number.

Something along the lines of this pseudo code:

SELECT NumSeriesCurrent 
FROM NumSeries 
(UPDATE NumSeries SET NumSeriesCurrent = NumSeriesCurrent+1) 
WHERE NumSeriesKey='X'

Upvotes: 2

Views: 192

Answers (1)

Martin Smith
Martin Smith

Reputation: 453142

To update the value and get the value in NumSeriesCurrent previous to the update you can use

UPDATE NumSeries 
SET NumSeriesCurrent += 1
OUTPUT DELETED.NumSeriesCurrent
WHERE NumSeriesKey='X'

Upvotes: 5

Related Questions