Can I Select and Update at the same time?

后端 未结 6 1671
梦谈多话
梦谈多话 2021-01-19 00:07

This is an over-simplified explanation of what I\'m working on.
I have a table with status column. Multiple instances of the application will pull the contents of the f

6条回答
  •  庸人自扰
    2021-01-19 00:20

    You could use the OUTPUT statement.

    DECLARE @Table TABLE (ID INTEGER, Status VARCHAR(32))
    INSERT INTO @Table VALUES (1, 'New')
    INSERT INTO @Table VALUES (2, 'New')
    INSERT INTO @Table VALUES (3, 'Working')
    
    UPDATE  @Table
    SET     Status = 'Working'
    OUTPUT  Inserted.*
    FROM    @Table t1
            INNER JOIN (
              SELECT  TOP 1 ID 
              FROM    @Table
              WHERE   Status = 'New'
            ) t2 ON t2.ID = t1.ID
    

提交回复
热议问题