I recently faced an issue related to managing and maintaining my system-versioned temporal tables. Out of the blue, our dev/test database was full of weird tables. Dozens of them. With those long names, 'MSSQL_TemporalHistoryFor_' followed by several numbers and letters.
The source was obvious: they were historical tables that work together with the temporal ones to keep track of data versioning. But why so many and what should we do with them?
The Basics
Whenever we create a temporal table, a historical object will be created and linked to the main table. While the main object keeps the current version of each row, the historical object stores the old versions of each row and the timespan when it was valid.
If you do not specify the name of the historical object when you create the temporal table, the engine will create a new table with the name "MSSQL_TemporalHistoryFor_[object_id]_[suffix]". I understand it is a good practice to give a proper name to the historical object, explicitly referencing the main one and adding a suffix to tell it holds historical data. You can do that either that object already exists or not. If it doesn't, the engine will also create a new table, but this time using the name you specified in the SQL create statement.
CREATE TABLE dbo.myTemporalTab(
id bigint NOT NULL,
Description varchar(200),
initdate datetime NOT NULL,
SysStartTime datetime2(7) GENERATED ALWAYS AS ROW START NOT NULL,
SysEndTime datetime2(7) GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime),
CONSTRAINT PK_test PRIMARY KEY CLUSTERED (id )
)
WITH (SYSTEM_VERSIONING = ON )
-- to properly name your history table, replace the line above with this one:
-- WITH (SYSTEM_VERSIONING = ON ( HISTORY_TABLE = dbo.myTemporalTab_HISTORY ) )
GO
Once your temporal table is created, every time a record is updated or deleted, the old version of the record will move to the history table, including the proper timestamps to identify the period when that version was valid.
You can identify temporal tables in several ways. One of them is through SSMS, as shown below. As you see, table is tagged as system-versioned and it also references the associated historical table.
Recently a customer asked me for help with setting up a test of an Azure SQL Database in the single database tier with Geo-Replication to work with Transparent Data Encryption (TDE) with a customer-managed key, also known as Bring Your Own Key (BYOK). It is very simple to do it when you use service-managed keys, […]