Swapping ms-sql tables

前端 未结 6 2051
执笔经年
执笔经年 2021-02-05 08:17

I want to swap to tables in the best possible manner.
I have an IpToCountry table, and I create a new one on a weekly basis according to an external CSV file which I import.

6条回答
  •  别跟我提以往
    2021-02-05 09:00

    I've had problems getting partitioning functions to work at scale. CREATE and DROP PARTITION are blocking operations, and you have little control over the blocking, and if it can't get a lock it will fail with a severity level 16 and kill your connection -- which you can't trap and retry without reestablishing the connection. But it might work just fine for you. Also, MSS Enterprise Edition is required, you can't use SE -- might be too much for some smaller or more cost-concerned shops.

    I've also found the view redef to block at high-scale (= transaction volume + sheer volume of constantly-inserted data, in my case) on sys tables and objects, so those operations can deadlock on things like reindexing and DTCCs -- and in one case, specifically with a user in SSMS (of all things) trying to browse views in the Object Explorer (somebody needs to tell those guys about READPAST). Again, your mileage may vary.

    In contrast, the sp_rename works well for me at scale: it gives you control over the locking and the scope of it. To solve the blocking issue prior to the swap, try it as shown below. At face value this would seem to have the same scale issue at high volume... but I haven't seen it in practice. So, works for me... but again, everybody's needs and experiences are different.

    DECLARE @dummylock bit 
    BEGIN TRANSACTION 
    BEGIN TRY
       -- necessary to obtain exclusive lock on the table prior to swapping
       SELECT @dummylock = 1 WHERE EXISTS (SELECT 1 FROM A WITH (TABLOCKX))
       -- may or may not be necessary in your case
       SELECT @dummylock = 1 WHERE EXISTS (SELECT 1 FROM B WITH (TABLOCKX))
       exec sp_rename 'A', 'TEMP'
       exec sp_rename 'B', 'A'
       exec sp_rename 'TEMP', 'B'
       COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
       -- other error handling here if needed
       ROLLBACK TRANSACTION 
    END CATCH
    

提交回复
热议问题