SQL Server optimistic locking - Returning changed timestamp value

六眼飞鱼酱① 提交于 2019-12-22 10:48:35

问题


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.


回答1:


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



回答2:


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

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


来源:https://stackoverflow.com/questions/5312847/sql-server-optimistic-locking-returning-changed-timestamp-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!