安全存储过程更新

时间:2013-05-30 10:53:20

标签: sql sql-server tsql

我有存储过程:

ALTER PROCEDURE [dbo].[myDbProcedure]
@ID int

AS
BEGIN 
SET NOCOUNT ON;

IF EXISTS (SELECT * FROM [myDB] WHERE @ID = [ID])
UPDATE [myDB]
SET [count] = [count] - 1
, [paymentCount]  = [paymentCount]  + 1
WHERE @ID = [ID] 

END

现在我想要安全,如果100个人同时更新表格中没有错过任何信息

1 个答案:

答案 0 :(得分:2)

不知道我是否完全理解你的要求:

Begin Tran
    IF EXISTS (SELECT * FROM [myDB] WHERE @ID = [ID])
    UPDATE [myDB]
    SET [count] = [count] - 1
    , [paymentCount]  = [paymentCount]  + 1
    WHERE @ID = [ID] 
Commit

只有在寄存器实际存在的情况下,才会考虑删除if。通过这种方式,您将获得本质上在事务上下文中运行的更新。考虑查看隔离级别(来自注释:set transaction isolation level serializable)。