1

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

4

4 回答 4

3

这里

为了使表成为系统版本表,它需要以下内容:

  • 一个主键
  • 表选项 SYSTEM_VERSIONING 设置为 ON
  • 两个不可为空的 DATETIME2() 列,表示行有效期的开始和结束
    • 起始列应标有 GENERATED ALWAYS AS ROW START 选项
    • 结束列应标有选项 GENERATED ALWAYS AS ROW END
  • 期间列的指定:PERIOD FOR SYSTEM_TIME (, )
  • 一个链接的历史表(SQL Server 可以为你创建)来保存修改行的过去状态
于 2015-09-22T05:00:23.067 回答
2

你可以参考这两个链接:

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

归功于上面的源代码链接。

于 2015-09-22T05:21:30.187 回答
1

通过使用 System_versioning=ON 它会自动分配系统表名,但如果你想明确提到你的系统表,如下所示

--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
于 2017-12-16T22:21:12.353 回答
0

请参考示例案例,了解如何根据每个场景在 SQL Server 中创建时态表。

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

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 的数据库表及其对应的历史表

于 2015-10-05T07:16:22.043 回答