sql-servert-sqlsql-server-2016temporal-tablessp-msforeachtable

How to clear all system versioned tables in one query?


I have a query which allows me to delete all rows and reset all indentity columns of all of my tables without breaking any foreign key references. This query works great for normal SQL Server tables:

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';
EXEC sp_MSForEachTable 'DELETE FROM ?';
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL';
EXEC sp_MSforeachtable @command1 = 'DBCC CHECKIDENT (''?'', RESEED, 0)';

The problem is, that now that I'm using system versioned temporal tables, the previous query doesn't work anymore. My versioned tables are all named tbl_Foo and every history table is in the format tbl_Foo_history.

I tried using something like this:

EXEC sp_MSForEachTable 'ALTER TABLE ? SET (SYSTEM_VERSIONING = OFF)';

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL';
EXEC sp_MSForEachTable 'DELETE FROM ?';
EXEC sp_MSForEachTable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL';
EXEC sp_MSforeachtable @command1 = 'DBCC CHECKIDENT (''?'', RESEED, 0)';

EXEC sp_MSforeachtable 'ALTER TABLE ? SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = ''?''_history))';

but it gives the error:

SYSTEM_VERSIONING is not turned ON for table 'FOO.dbo.tbl_Foo_history'.

because the sp_MSForEachTable obviously gets really messed up when trying to remove versioning from a history table.

How should I do this without specifying the queries individually for every single table?


Solution

  • I solved the problem with just creating the same queries for each of my tables with a Vim macro. It looks ugly, but in practice was very quick to implement:

    ALTER TABLE dbo.tbl_Foo1 SET (SYSTEM_VERSIONING = OFF);
    ALTER TABLE dbo.tbl_Foo2 SET (SYSTEM_VERSIONING = OFF);
    ALTER TABLE ...
    
    ALTER TABLE dbo.tbl_Foo1 NOCHECK CONSTRAINT ALL;
    ALTER TABLE dbo.tbl_Foo2 NOCHECK CONSTRAINT ALL;
    ALTER TABLE ...
    
    DELETE FROM dbo.tbl_Foo1;
    DELETE FROM dbo.tbl_Foo2;
    DELETE FROM ...
    
    DELETE FROM dbo.tbl_Foo1_history;
    DELETE FROM dbo.tbl_Foo2_history;
    DELETE FROM ...
    
    DBCC CHECKIDENT ('[tbl_Foo1]', RESEED, 0);
    DBCC CHECKIDENT ('[tbl_Foo2]', RESEED, 0);
    DBCC CHECKIDENT ...
    
    DBCC CHECKIDENT ('[tbl_Foo1_history]', RESEED, 0);
    DBCC CHECKIDENT ('[tbl_Foo2_history]', RESEED, 0);
    DBCC CHECKIDENT ...
    
    ALTER TABLE dbo.tbl_Foo1 WITH CHECK CHECK CONSTRAINT ALL;
    ALTER TABLE dbo.tbl_Foo2 WITH CHECK CHECK CONSTRAINT ALL;
    ALTER TABLE ...
    
    ALTER TABLE dbo.tbl_Foo1 SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.tbl_Foo1_history));
    ALTER TABLE dbo.tbl_Foo2 SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.tbl_Foo2_history));
    ALTER TABLE ...