302 words
2 minutes
SQL Server Temporal Tables
System Version Query — How To
SELECT *FROM dbo.MyTable
--( at time zone does not work on literals, use var to work around this limitation )--DECLARE @AsOf DATETIME2 = '4/8/2019 9:43AM'SELECT @AsOf = @AsOf AT TIME ZONE 'Eastern Standard Time' AT TIME ZONE 'UTC'
SELECT *FROM dbo.MyTableFOR SYSTEM_TIME AS OF @AsOf --( includes changes where the record was valid during the given time )----FOR SYSTEM_TIME ALL --( includes all changes )----FOR SYSTEM_TIME FROM @StartDate TO @EndDate --( exclusive of start and end dates )----FOR SYSTEM_TIME BETWEEN @StartDate AND @EndDate --( inclusive of start and end dates )--
--( query directly from the history table )--SELECT *FROM dbo.MyTableHistoryEnable System Versioning
This snippet will add the required columns ValidFrom and ValidTo and enable system versioning with a history table of {Schema}.{TableName}History.
DECLARE @TableName SYSNAME = 'MyTable', @TableSchema SYSNAME = 'dbo', @IsDebug BIT = 0
DECLARE @Sql NVARCHAR(MAX) = ''
--( add sys version columns and enable )--SELECT @Sql = 'ALTER TABLE [{0}].[{1}]ADD [ValidFrom] DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN NOT NULL CONSTRAINT [DF[{0}]].[{1}]].[ValidFrom]]] DEFAULT (sysutcdatetime()),[ValidTo] DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN NOT NULL CONSTRAINT [DF[{0}]].[{1}]].[ValidTo]]] DEFAULT (CONVERT([datetime2](0),''9999-12-31 23:59:59'')),PERIOD FOR SYSTEM_TIME([ValidFrom], [ValidTo])
ALTER TABLE [{0}].[{1}]SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [{0}].[{1}History]));'SELECT @Sql = REPLACE(@Sql, '{0}', @TableSchema)SELECT @Sql = REPLACE(@Sql, '{1}', @TableName)
IF @IsDebug = 1 PRINT (@Sql)IF @IsDebug = 0 EXEC (@Sql)Disable System Versioning
This will disable system versioning on the given table.
DECLARE @TableName SYSNAME = 'MyTable', @TableSchema SYSNAME = 'dbo', @IsDebug BIT = 0
DECLARE @Sql NVARCHAR(MAX) = ''
SELECT @Sql = 'ALTER TABLE [{0}].[{1}]SET (SYSTEM_VERSIONING = OFF)'SELECT @Sql = REPLACE(@Sql, '{0}', @TableSchema)SELECT @Sql = REPLACE(@Sql, '{1}', @TableName)
IF @IsDebug = 1 PRINT (@Sql)IF @IsDebug = 0 EXEC (@Sql)~ SK
SQL Server Temporal Tables
https://www.kichka.dev/posts/sql-temporal-tables/