0

我有一个查询,它允许我删除所有行并重置所有表的所有缩进列,而不会破坏任何外键引用。此查询适用于普通 SQL Server 表:

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)';

问题是,现在我使用的是系统版本的时态表,以前的查询不再起作用。我的版本化表都已命名tbl_Foo,每个历史表都采用tbl_Foo_history.

我尝试使用这样的东西:

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))';

但它给出了错误:

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

因为sp_MSForEachTable当试图从历史表中删除版本控制时,显然会变得非常混乱。

如果不为每个表单独指定查询,我应该如何做到这一点?

4

1 回答 1

0

我解决了这个问题,只需使用 Vim 宏为我的每个表创建相同的查询。它看起来很难看,但实际上实现起来非常快:

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 ...
于 2019-06-20T11:06:31.117 回答