Versioning in SQL Tables - how to handle it?

前端 未结 7 1242
囚心锁ツ
囚心锁ツ 2021-01-30 08:50

Here\'s a fictional scenario with some populated data. For tax purposes, my fictional company must retain records of historical data. For this reason, I\'ve included a version c

7条回答
  •  终归单人心
    2021-01-30 09:33

    Although the question has been asked 8 years ago, it worths to mention there is feature exactly for this in SQL Server 2016. System-versioned Temporal Table

    Every table in SQL Server 2016 and above can have a history table, which the historical data will be populated automatically by SQL Server itself.

    All you need is to add two datetime2 columns and one clause to the table:

    CREATE TABLE Employee 
    (
        Id int NOT NULL PRIMARY KEY CLUSTERED,
        [Name] varchar(50) NOT NULL,
        Position varchar(50)  NULL,
        Pay money NULL,
        ValidFrom datetime2 GENERATED ALWAYS AS ROW START NOT NULL,
        ValidTo datetime2 GENERATED ALWAYS AS ROW END NOT NULL,
            PERIOD FOR SYSTEM_TIME (ValidFrom,ValidTo)
    )  
    WITH (SYSTEM_VERSIONING = ON);
    

    The system versioned table creates a temporal table which maintains the history of the data. You can use a custom name WITH (SYSTEM_VERSIONING = ON ( HISTORY_TABLE = dbo.EmployeeHistory ) );

    In this link you can find more details about System-version temporal tables.

    As @NotMe mentioned, historical tables can be grow very fast, so there are a few ways to get around this. Take a look here

提交回复
热议问题