SQL 2016 年的服务器时态表

SQL Server temporal tables in 2016

当我想在 SQL Server 2016 中创建新的临时 table 时,我想知道如何创建系统版本 table?

来自here

In order to make a table a system-versioned table it needs the following:

  • A primary key
  • The table option SYSTEM_VERSIONING to be set to ON
  • Two non-nullable DATETIME2() columns representing the start and end of the row’s validity period
    • The start column should be marked with the option GENERATED ALWAYS AS ROW START
    • The end column should be marked with the option GENERATED ALWAYS AS ROW END
  • Designation of the period columns: PERIOD FOR SYSTEM_TIME (, )
  • A linked history table (which SQL Server can create for you) to hold the past states of modified rows

可以参考这两个link:

http://sqlmag.com/sql-server/first-look-system-versioned-temporal-tables-part-1-creating-tables-and-modifying-data

http://blogs.msdn.com/b/manub22/archive/2015/06/30/temporal-data-with-system-versioned-tables-in-sql-server-2016.aspx

http://sqlwithmanoj.com/2015/06/15/temporal-data-support-in-sql-server-2016-part-1/

    USE [TestManDB]
    GO

    CREATE TABLE dbo.Department 
    (
    DepartmentID        int NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED, 
    DepartmentName      varchar(50) NOT NULL, 
    ManagerID           int 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 ); -- No History table name given here
    GO

感谢上面 link 的源代码。

请根据每个场景参考how to create temporal tables in SQL Server处的案例。

最简单的形式是创建一个新的 SQL table 作为时间 table,如下所示

create table sampleTable (
  IdColumn int identity(1,1) not null primary key clustered,
  Code varchar(5),
  CurrentValue varchar(100),
  SysStartTime datetime2 Generated Always as Row Start Not Null,
  SysEndTime datetime2 Generated Always as Row End Not Null,
  Period for System_Time (SysStartTime, SysEndTime)
 )
 with (System_Versioning = ON) 

这将在当前数据库

中创建一个名为 sampleTable 的数据库 table 及其对应的历史记录 table

通过使用 System_versioning=ON 它将自动分配系统 table 名称,但如果您想明确提及您的系统 table 如下所示

--create table or use existing table
CREATE TABLE [dbo].[table1](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](255) NOT NULL,
    [updated_at] [datetime] NULL
)

GO
--Adding additional field for temporal tables
alter table dbo.table1
add start_time DATETIME2 generated always as row start hidden default sysutcdatetime()
    ,end_time DATETIME2 generated always as row end hidden default sysutcdatetime()
    ,period for system_time (start_time, end_time)
go

--enable system versioning
alter table dbo.table1
set (system_versioning = ON ( history_table = dbo.table1_history))
go