Temporal tables are a new feature in SQL Server 2016 that allow the storage of historical data in a simple way, without the need for complex queries or custom code. A temporal table is a database table that stores the history of data changes over time. When a row is updated or deleted, a new row is created in the table to store the old values, along with the new values in the original row. This allows for easy auditing and recovery of data from previous points in time, without having to rely on backups or custom code.
To create a temporal table in SQL Server, you need to specify the history table and the period columns. The history table is a separate table that stores the historical data, and the period columns represent the time range during which the data was valid. Here is an example:
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY,
Name VARCHAR(50),
Email VARCHAR(50),
ValidFrom DATETIME2(0) GENERATED ALWAYS AS ROW START,
ValidTo DATETIME2(0) GENERATED ALWAYS AS ROW END,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.CustomersHistory));
In this example, the Customers table has two period columns (‘ValidFrom‘ and ‘ValidTo‘) that define the time range during which each row was valid. The ‘SYSTEM_VERSIONING‘ clause specifies that the table is a temporal table, and the ‘HISTORY_TABLE‘ option specifies the name of the history table.
One of the main benefits of temporal tables is their ability to simplify auditing and compliance. By storing historical data in the same table, you can easily track changes to your data over time and meet regulatory requirements. Additionally, temporal tables can make it easier to recover lost data because you can retrieve previous versions of the data by querying the history table.
Another benefit is that temporal tables allow for easy analysis of changes over time. For example, you can easily create reports that show how data has changed over a certain period, or how often certain data has been changed. This can be valuable for trend analysis, troubleshooting, and other purposes.
Overall, temporal tables are a powerful feature that simplify data auditing and analysis, while also reducing the need for custom code and complex queries.