Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server optimistic locking - Returning changed timestamp value

I have an update stored procedure that implements optimistic locking. The stored procedure looks like this:

ALTER PROCEDURE [dbo].[usp_Test] 
    @Id AS char(2),
       @recordTimestamp as timestamp
       ...
BEGIN       
    UPDATE XY
           ..
          WHERE ((Id = @Id) AND (recordTimeStamp = @recordTimestamp))       

if @@rowcount = 0
begin
RAISERROR ('this row was changed by another user', 18, 1)
end

SELECT timeStamp from XY where Id = @Idend

Is there a simpler way to return the new timestamp? I would really like to avoid the SELECT statement.

like image 580
Sebastjan Avatar asked Apr 12 '26 09:04

Sebastjan


1 Answers

Assuming at least SQL Server 2005 you can use OUTPUT

UPDATE XY
SET Col = 'foo'
OUTPUT inserted.recordTimeStamp
WHERE ((Id = @Id) AND (recordTimeStamp = @recordTimestamp))    

Or a version that uses a table variable to more closely mirror the behaviour of the original query.

DECLARE @Timestamp TABLE(stamp binary(8))

UPDATE XY
SET col='foo'
OUTPUT inserted.recordTimeStamp INTO @Timestamp
WHERE (Id = @Id) AND (recordTimeStamp = @recordTimestamp) 

if @@rowcount = 0
begin
RAISERROR ('this row was changed by another user', 18, 1)
end

SELECT stamp 
FROM @Timestamp
like image 145
Martin Smith Avatar answered Apr 13 '26 23:04

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!