Search code examples
sqlsql-serversql-server-2016temporal-databasetemporal-tables

How can alter existence tables to SQL Temporal table by keeping data?


I have many table with data, which I want to convert to Microsoft Temporal table, But when I want to convert temporal table cause lost my data. My code is:

Alter TABLE dbo.Employee   
(    
  [EmployeeID] int NOT NULL PRIMARY KEY CLUSTERED   
  , [Name] nvarchar(100) NOT NULL  
  , [Position] varchar(100) NOT NULL   
  , [Department] varchar(100) NOT NULL  
  , [Address] nvarchar(1024) NOT NULL  
  , [AnnualSalary] decimal (10,2) NOT NULL  
  , [ValidFrom] datetime2 (2) GENERATED ALWAYS AS ROW START  
  , [ValidTo] datetime2 (2) GENERATED ALWAYS AS ROW END  
  , PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)  
 )    
 WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistory)); 

how can alter existence tables to Sql temporal table by keeping data?


Solution

  • First you should add two columns for system time period to any tables. like this:

    CREATE TABLE DepartmentHistory   
    (    
         DeptID int NOT NULL  
       , DeptName varchar(50) NOT NULL  
       , SysStartTime datetime2 NOT NULL  
       , SysEndTime datetime2 NOT NULL   
    );   
    GO   
    CREATE CLUSTERED COLUMNSTORE INDEX IX_DepartmentHistory   
       ON DepartmentHistory;   
    CREATE NONCLUSTERED INDEX IX_DepartmentHistory_ID_PERIOD_COLUMNS   
       ON DepartmentHistory (SysEndTime, SysStartTime, DeptID);   
    GO   
    CREATE TABLE Department   
    (    
        DeptID int NOT NULL PRIMARY KEY CLUSTERED  
       , DeptName varchar(50) NOT NULL  
       , SysStartTime datetime2  NOT NULL  
       , SysEndTime datetime2 NOT NULL           
    ) ;
    

    In the up codes, SysStartTime and SysEndTime has system period time columns.

    Then you can convert them to Temporal tables easily:

    ALTER TABLE dbo.Department   
       ADD PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])   
    ALTER TABLE dbo.Department      
       SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.DepartmentHistory, DATA_CONSISTENCY_CHECK = ON));  
    

    And, if you have temporal table and you want to edit tables schema, so you can do it by this code:

    ALTER TABLE Test.dbo.Department   
       SET (SYSTEM_VERSIONING = OFF)