当我想在SQL Server 2016中创建新的时态表时,我想知道如何创建系统版本的表?
答案 0 :(得分:3)
来自here:
为了使表成为系统版本的表,它需要 以下内容:
- 主键
- 要将表选项SYSTEM_VERSIONING设置为ON
- 两个不可为空的DATETIME2()列,表示行有效期的开始和结束
- 起始栏应标有选项GENERATED ALWAYS AS ROW START
- 结束列应标有选项GENERATED ALWAYS AS ROW END
- 期间列的指定:PERIOD FOR SYSTEM_TIME(,)
- 链接历史记录表(SQL Server可以为您创建)以保存已修改行的过去状态
答案 1 :(得分:2)
您可以参考以下两个链接:
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
在上面的链接中输入源代码。
答案 2 :(得分: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
答案 3 :(得分:0)
请根据每种情况参考how to create temporal tables in 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的数据库表及其在当前数据库中的相应历史表