Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock table while inserting

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 procedure is run every so often that updates the table.

 TRUNCATE TABLE LargeTable

 INSERT INTO LargeTable
 SELECT * 
 FROM viewLargeView
 WITH (HOLDLOCK)

I would like to lock this table when inserting so if someone tries to select a record they will not receive none after the truncate. The lock I am using seems to lock the view and not the table.

Is there a better way to approach this problem?

like image 527
JBone Avatar asked Mar 23 '12 15:03

JBone


People also ask

How do you lock a table during insert?

Place an insert lock in the table to which the row is being added. Insert locks are exclusive, so once the insert lock is acquired, no other isolation level 3 transaction can block the insertion by acquiring a phantom lock. Write lock the new row. The insert lock is released once the write lock has been obtained.

How do I lock a table while inserting in SQL Server?

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.

Does insert statement lock the table?

When inserting a record into this table, does it lock the whole table? Not by default, but if you use the TABLOCK hint or if you're doing certain kinds of bulk load operations, then yes.

Does MySQL lock table while inserting?

MySQL uses table locking (instead of row locking or column locking) on all table types, except InnoDB and BDB tables, to achieve a very high lock speed.


2 Answers

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.

like image 178
Andomar Avatar answered Oct 31 '22 02:10

Andomar


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
like image 30
Darren Avatar answered Oct 31 '22 02:10

Darren