我有很多带有数据的表,我想将其转换为Microsoft Temporal表,但是当我要转换时态表时,会丢失我的数据。
我的代码是:

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));

如何通过保留数据将存在表更改为Sql临时表?

最佳答案

首先,您应该在任何表中添加两列以表示系统时间段。
像这样:

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
) ;

在向上代码中,SysStartTimeSysEndTime具有系统周期时间列。

然后,您可以轻松地将它们转换为时间表:
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));

并且,如果您有临时表,并且想要编辑表架构,那么可以通过以下代码进行操作:
ALTER TABLE Test.dbo.Department
   SET (SYSTEM_VERSIONING = OFF)

10-04 21:35
查看更多