Lock table while inserting

前端 未结 2 642
长情又很酷
长情又很酷 2020-12-29 13:31

I have a large table that get populated from a view. This is done because the view takes a long time to run and it is easier to have the data readily available in a table. A

相关标签:
2条回答
  • 2020-12-29 13:54
    BEGIN TRY
     BEGIN TRANSACTION t_Transaction
    
     TRUNCATE TABLE LargeTable
    
     INSERT INTO LargeTable
     SELECT * 
     FROM viewLargeView
      WITH (HOLDLOCK)
    
     COMMIT TRANSACTION t_Transaction
    END TRY 
    BEGIN CATCH
      ROLLBACK TRANSACTION t_Transaction
    END CATCH
    
    0 讨论(0)
  • 2020-12-29 14:12

    It's true that your correct locking hint affects the source view.

    To make it so that nobody can read from the table while you're inserting:

    insert into LargeTable with (tablockx)
    ...
    

    You don't have to do anything to make the table look empty until after the insert completes. An insert always runs in a transaction, and no other process can read uncommitted rows, unless they explicitly specify with (nolock) or set transaction isolation level read uncommitted. There is no way to protect from that as far as I know.

    0 讨论(0)
提交回复
热议问题