Recalculate and replace large table without interrupting table reads

azure-sql-databaselockingselect

There's a large table in the database containing statistical information. This table must be read frequently (by lookups which return a single row).

This table must be completely recalculated every so often. There's a procedure which does the calculation. Currently it does this into a temporary table, and then when it's done it truncates the real table and inserts the data from the temporary table into it.

The problem is that this truncation and insertion takes a while and interrupts lookups during that time. The question is how to do it without interrupting lookups, or only interrupting lookups very briefly.

I'd be happy to hear all options which achieve the desired behaviour; the solution doesn't necessarily have to involve a temporary table. Sorry if this is an established common problem — I wasn't sure which terms to search.

Best Answer

Two options, depending on the engine and/or the permissions you have - populate a second table, then rename that table (e.g. sp_rename 'thetable', 'deadtable'; sp_rename 'newtable', 'thetable'; drop table deadtable;), or populate a second table then have your application choose to use that table instead.