0

I have 62 tables that were set up as system-versioned/temporal tables except the start and end time columns were set up as datetime2(0) as shown below.

SysStartTime [datetime2](0) GENERATED ALWAYS AS ROW START NOT NULL,
SysEndTime [datetime2](0) GENERATED ALWAYS AS ROW END NOT NULL,

Because of this, we have records within the history table that appear to be duplicated because we lose the necessary precision when records were modified multiple times by our system. I haven't been able to find any documentation on modifying those two columns, but tried the following code:

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

However, I still get the following error:

Period column 'SysStartTime' in a system-versioned temporal table cannot be altered.

Is there a way to alter those two columns and set it to datetime2(7)?

4

1 回答 1

1

下面的脚本对我有用(当然你需要用你的值替换 {tableSchema}、{tableName}、{historyTableSchema}、{historyTableName})。

该脚本将 SysStartTime 和 SysEndTime 的新精度设置为 7。

请注意 SysEndTime 列如何需要具有给定精度的最大 DATETIME2 值(因此是 UPDATE)。

还要注意在定义临时表时默认创建的索引 ix_{historyTableName} 如何需要被删除和重新创建。

请参阅以供参考:https ://docs.microsoft.com/en-us/sql/relational-databases/tables/creating-a-system-versioned-temporal-table?view=sql-server-ver15#migrate-existing-表到内置支持

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
于 2021-03-29T05:44:04.137 回答