Wednesday, December 16, 2015

SQL Server 2016: Temporal Tables

Temporal tables in SQL Server 2016 is a new type of user table. It was introduced in ISO/ANSI SQL 2011.

Temporal tables keep a full history of data changes (based on UTC time) by using a pair of current-historical tables. These tables has the same structure.

The period of validity for every row is managed by the system (i.e. Database Engine) by using two explicitly-defined columns of the DateTime2 datatype.

Below you can find an example of a user table's definition that has system versioning enabled:

--Create table along with specifying its historical table
CREATE TABLE dbo.Students2
(
  studentID INT NOT NULL IDENTITY(1,1) CONSTRAINT PK_Students PRIMARY KEY,
  studentName VARCHAR(150) NOT NULL,
  studentAddress VARCHAR(150) NOT NULL,
  regDate DATE NOT NULL,
  SysStartTime DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL,
  SysEndTime DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL,
  PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.Students2History));
GO

The above DDL will create two tables: (i) Students2, and (ii) Students2History.

In the "dbo.Students2" table, the user needs to populate only the first 4 columns (studentID, studentName, studentAddress and regDate). Note: In this case "studentID" will be populated automatically too because it is an identity column. The rest of the columns will be maintained automatically by SQL Server's Database Engine. Table "dbo.Students2History" will be populated fully automatically by the Database Engine.

In the below screenshot we can see both tables:

Figure 1: Pair of Current-Historical Table



































Let's check both tables for any contents:

Figure 2: Table Contents.
























Now, let's insert some data in the "dbo.Students2" table:

--Insert initial data
INSERT INTO dbo.Students2
        ( studentName ,
          studentAddress ,
          regDate 
        )
VALUES  ( 'John Adams', 
          'Address 1', 
          GETDATE() 
        );
GO

Let's check again both tables for any contents:

Figure 3: Table Contents After Insert.






















As you can see, the "dbo.Students2" table was populated with data.

The "dbo.Students2History" table was not populated with any data because system versioning works only in case of an update operation against one or more rows.

That being said, let's try to update the row:

--Now let's update a record
UPDATE dbo.Students2
SET studentAddress='Address 1 Update'
WHERE studentID=1;
GO

Let's check again the table contents:

Figure 4: Table Contents After Update Operation.





















Now you can see that the table "Students2History" contains the original values for row with studentID=1 just before the update operation took place.

Let's update the same record again:

--Update the same record
UPDATE dbo.Students2
SET studentAddress='Address 1 Update 2'
WHERE studentID=1;
GO

Let's check the table contents:

Figure 5: Table Contents After Second Update.























As you can see, the table "Students2History" contains also the "new" original value for row with studentID=1 just before the new update operation took place. So in total, the historical table contains the rows for studentID=1 just before the two update operations took place. The validity of each row can be determined from the "SysStartTime" and "SysEndTime" values.


This article was a simple example of using temporal tables in SQL Server 2016. I consider temporal tables one of the top new features in SQL Server 2016 as they have to offer significant functionality.

Some benefits of using temporal tables:
  • Auditing all data changes (i.e. for data forensics)
  • Data reconstruction/recovery
  • Trends monitoring over time


[Ads]
Check out my latest eBook on SQL Server:
Tuning SQL Server - Ebook

Easily secure your SQL Server instances! Try out DBA Security Advisor!
DBA Security Advisor for SQL Server by SQLArtBits
DBA Security Advisor was developed by SQLArtBits. The tool was being carefully developed for an entire year and it contains comprehensive security checks and recommendations based on proven SQL Server security best practices. Feel free to download and use the Community Edition which is free and if you find it useful, you can consider upgrading to the Enterprise Edition!

Artemakis Artemiou [MVP]

Author & Editor

Artemakis Artemiou is a Senior SQL Server Architect, Software Developer and Microsoft Data Platform MVP. He is also an author, regular blogger, president of Cyprus.NET User Group and CY Country leader of INETA-EU. He is also the creator of DBA Security Advisor and In-Memory OLTP Simulator. Artemakis is a frequent guest author of worldwide well-respected online journals where he writes articles focusing on many SQL Server topics.

Reference: The SQL Server and .NET Hub (http://www.sqlnethub.com)

0 comments: