Select rows and Update same rows for locking?

前端 未结 2 1560
不思量自难忘°
不思量自难忘° 2021-01-21 15:02

I need to write a procedure that will allow me to select x amount of rows and at the same time update those rows so the calling application will know those records are locked an

2条回答
  •  盖世英雄少女心
    2021-01-21 15:37

    Vote for Cade Roux's answer, using OUTPUT:

    UPDATE #tbl
       SET locked = 1
    OUTPUT INSERTED.*
     WHERE id IN (SELECT TOP 1 id
                    FROM #tbl
                   WHERE locked = 0
                ORDER BY id)​
    

    Previously:


    This is one of the few times I can think of using a temp table:

    ALTER PROCEDURE temp_table_test
    AS
    BEGIN
    
       SELECT TOP 5000 * 
         INTO #temp_test
         FROM your_table
        WHERE locked != 1
     ORDER BY ?
    
       UPDATE your_table
          SET locked = 1
        WHERE id IN (SELECT id FROM #temp_test)
    
       SELECT *
         FROM #temp_test
    
       IF EXISTS (SELECT NULL
                    FROM tempdb.dbo.sysobjects
                   WHERE ID = OBJECT_ID(N'tempdb..#temp_test'))
       BEGIN
         DROP TABLE #temp_test
       END
    
    END
    

    This:

    1. Fetches the rows you want, stuffs them into a local temp table
    2. Uses the temp table to update the rows to be "locked"
    3. SELECTs from the temp table to give you your resultset output
    4. Drops the temp table because they live for the session

提交回复
热议问题