Get Temporal Table Setup



CREATE PROCEDURE [dbo].[usp_utl_GetTemporalTableSetup]
    @TableSchema sysname
  , @TableName sysname
  , @HistoryTableSchema sysname OUTPUT
  , @HistoryTableName sysname OUTPUT
  , @PeriodColumnName sysname OUTPUT
  , @debug BIT = 0
AS
-- =============================================
-- Author: Mihir Shah (UHC\mshah1)
-- Create date: 13/07/2018
-- Purpose: Purpose of this Stored procedure is to
/*
--Get the details of the temporal table, e.g. the name of it's history table.

--Example of usage:
-- declare @HistoryTableSchema sysname, @HistoryTableName sysname , @PeriodColumnName sysname;
-- exec usp_utl_GetTemporalTableSetup @TableSchema='raw', @TableName = 'C_Roster'
-- , @HistoryTableSchema=@HistoryTableSchema output, @HistoryTableName=@HistoryTableName output, @PeriodColumnName=@PeriodColumnName output
-- , @debug = 1
-- print concat('@HistoryTableSchema = ', @HistoryTableSchema, ', @HistoryTableName = ',  @HistoryTableName, ', = @PeriodColumnName = ', @PeriodColumnName)
*/

-- =============================================
BEGIN
    SET NOCOUNT ON;

    IF (LEN(@TableSchema) > 0 AND   LEN(@TableName) > 0)
    BEGIN
        EXECUTE sp_executesql N'SELECT @hst_tbl_nm = t2.name, @hst_sch_nm = s.name, @period_col_nm = c.name 
FROM sys.tables t1 
   JOIN sys.tables t2 on t1.history_table_id = t2.object_id 
JOIN sys.schemas s on t2.schema_id = s.schema_id 
JOIN sys.periods p on p.object_id = t1.object_id 
   JOIN sys.columns c on p.end_column_id = c.column_id and c.object_id = t1.object_id 
  WHERE 
t1.name = @tblName and s.name = @schName'
, N'@tblName sysname 
, @schName sysname 
, @hst_tbl_nm sysname OUTPUT 
, @hst_sch_nm sysname OUTPUT 
, @period_col_nm sysname OUTPUT'
, @tblName = @TableName
, @schName = @TableSchema
, @hst_tbl_nm = @HistoryTableName OUTPUT
, @hst_sch_nm = @HistoryTableSchema OUTPUT
, @period_col_nm = @PeriodColumnName OUTPUT;
    END;

END;



GO


Comments

Popular posts from this blog

Calculating Age of the person in T-SQL

How to Troubleshoot Subscription issue in Reporting Services

MDX Queries - Current Day - Month and Year