Insert Concurrency Issue - Multithreaded Environment

前端 未结 4 1633
有刺的猬
有刺的猬 2021-02-09 18:04

I have an issue that the same stored procedure is being invoked at exactly the same time with exactly the same paramenters.

The purpose of the stored procedure is to fet

4条回答
  •  北海茫月
    2021-02-09 18:45

    The trick is to add a WHERE to your INSERT statement so that INSERT only works if the item does not exist, followed by the SELECT statement. Supposing that the record can be identified by an ID column you would write:

    INSERT INTO MyTable (ID,Col1,Col2,...) 
    SELECT @IDValue,@Col1Value,@Col2Value, ...
    WHERE NOT EXISTS (SELECT ID  
                  FROM MyTable 
                  WHERE ID=@IDValue) 
    
    SELECT *  
    FROM MyTable 
    Where ID=@IDValue 
    

    You don't need to put the statements in a transaction because each statement is executed in its own implicit transaction. Thus, there is no way that two INSERTS will succeed at the same time.

    EDIT: The INSERT ... SELECT syntax is necessary because TSQL doesn't allow a VALUES and a WHERE part in the INSERT statement.

提交回复
热议问题