Optimistic SQL Server Lock - Returning a Modified Timestamp Value

I have a stored update procedure that implements optimistic locking. The stored procedure is as follows:

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 an easier way to return a new timestamp? I would really like to avoid the instructions SELECT.

+3
source share
2 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 accurately reflect the behavior 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
+7
source

Obviously, I was blind. @@ DBTS (http://msdn.microsoft.com/en-us/library/ms187366 (SQL.90) .aspx) is the right way.

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

All Articles