Detecting dirty reads from a stored procedure

前端 未结 8 523
自闭症患者
自闭症患者 2021-02-04 02:27

I\'ve got 100 threads that are each calling the stored procedure as defined below.

How do I prevent dirty reads?

SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS         


        
8条回答
  •  深忆病人
    2021-02-04 03:14

    If you need to update and return what you updated, then I would just use the OUTPUT clause:

    UPDATE CfgCerealNumber 
    SET CerealNumber = CerealNumber + 1 
    OUTPUT INSERTED.CerealNumber
    WHERE CerealNumberID = @TableID;
    

    If you need additional checking, you can OUTPUT into a declared table variable before returning the result set from the stored procedure.

    Another alternative would be to create a blocking lock on the table first, and then update:

    SELECT @CerealNumber = CerealNumber + 1 
    FROM CfgCerealNumber WITH (HOLDLOCK, UPDLOCK) 
    WHERE CerealNumberID = @TableID;
    
    UPDATE CfgCerealNumber
    SET CerealNumber = @CerealNumber
    WHERE CerealNumberID = @TableID;
    

    But I would put money down that I've seen this still cause problems. I trust it much less.

提交回复
热议问题