问题描述
除了开始和结束时间列设置为datetime2(0)
之外,我有62个表被设置为系统版本/时间表,如下所示。
SysstartTime [datetime2](0) GENERATED ALWAYS AS ROW START NOT NULL,SysEndTime [datetime2](0) GENERATED ALWAYS AS ROW END NOT NULL,
因此,历史记录表中的记录似乎是重复的,因为当系统多次修改记录时,我们失去了必要的精度。我找不到有关修改这两列的任何文档,但是尝试了以下代码:
ALTER TABLE SystemVersionedTable
SET (SYstem_VERSIONING = OFF);
ALTER TABLE SystemVersionedTable
ALTER COLUMN SysstartTime DATETIME2(7);
ALTER TABLE SystemVersionedTable
ALTER COLUMN SysEndTime DATETIME2(7);
ALTER TABLE SystemVersionedTable
SET (SYstem_VERSIONING = ON (HISTORY_TABLE = History.dbo_SystemVersionedTable));
但是,我仍然遇到以下错误:
系统版本化的时间表中的“ SysstartTime”列不能更改。
是否可以更改这两列并将其设置为datetime2(7)
?
解决方法
下面的脚本对我有用(当然你需要用你的值替换 {tableSchema}、{tableName}、{historyTableSchema}、{historyTableName})。
脚本将 SysStartTime 和 SysEndTime 的新精度设置为 7。
注意 SysEndTime 列如何需要具有给定精度的最大 DATETIME2 值(因此是 UPDATE)。
还要注意索引ix_{historyTableName}是如何在定义时态表时默认创建的,需要删除和重新创建。
BEGIN TRANSACTION
ALTER TABLE [{tableSchema}].[{tableName}] SET (SYSTEM_VERSIONING = OFF)
ALTER TABLE [{tableSchema}].[{tableName}] DROP PERIOD FOR SYSTEM_TIME
DROP INDEX [ix_{historyTableName}] ON [{historyTableSchema}].[{historyTableName}]
GO
ALTER TABLE [{tableSchema}].[{tableName}] ALTER COLUMN SysStartTime DATETIME2(7) NOT NULL
ALTER TABLE [{tableSchema}].[{tableName}] ALTER COLUMN SysEndTime DATETIME2(7) NOT NULL
ALTER TABLE [{historyTableSchema}].[{historyTableName}] ALTER COLUMN SysStartTime DATETIME2(7) NOT NULL
ALTER TABLE [{historyTableSchema}].[{historyTableName}] ALTER COLUMN SysEndTime DATETIME2(7) NOT NULL
CREATE CLUSTERED INDEX [ix_{historyTableName}] ON [{historyTableSchema}].[{historyTableName}] (SysEndTime,SysStartTime)
GO
UPDATE [{tableSchema}].[{tableName}] SET SysEndTime = CONVERT(DATETIME2(7),'9999-12-31 23:59:59.9999999')
GO
ALTER TABLE [{tableSchema}].[{tableName}] ADD PERIOD FOR SYSTEM_TIME (SysStartTime,SysEndTime)
ALTER TABLE [{tableSchema}].[{tableName}] SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [{historyTableSchema}].[{historyTableName}],DATA_CONSISTENCY_CHECK = ON))
GO
COMMIT TRANSACTION