SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE Snapshot_HistoryTable
-- Add the parameters for the stored procedure here
(@ID int,@AsofDate DATE)
AS
BEGIN TRY
BEGIN TRANSACTION
DECLARE --@ID int=133,@AsofDate DATE='2018-09-22',
@ControlRowId NVARCHAR(20),
@DATE1 nvarchar(20),
@sql_delete nvarchar(max),
@sql_insert nvarchar(max),
@source_table nvarchar(20)='DimAccount',
@Destination_table nvarchar(20)='DimAccount_History',
@SOURCE_combinedString NVARCHAR(MAX),
@DEST_combinedString NVARCHAR(MAX),
@combinedString NVARCHAR(MAX)
SELECT @ControlRowId=CAST(@ID AS NVARCHAR)
SELECT @DATE1=CAST(@AsofDate AS NVARCHAR)
set @sql_delete='delete from ' + @Destination_table +' where cast([_Createddate] as date)=cast(getdate() as date)'
execute sp_executesql @sql_delete
SELECT @SOURCE_combinedString = COALESCE(@SOURCE_combinedString + ', ', '') + column_name
FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@source_table AND column_name NOT LIKE '%KEY' ORDER BY column_name ASC
SELECT @DEST_combinedString = COALESCE(@DEST_combinedString + ', ', '') + column_name
FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@Destination_table AND column_name NOT LIKE '%KEY' AND column_name
NOT IN ('ControlRowId','_Createddate'
) ORDER BY column_name ASC
SET @combinedString='INSERT INTO ' + @Destination_table +'('+@DEST_combinedString + ',ControlRowId,_Createddate)'
+' SELECT ' + @SOURCE_combinedString +','+ @ControlRowId+','''+@DATE1+'''FROM '
+@source_table
PRINT @combinedString
execute sp_executesql @combinedString
COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT 'ERROR'
END CATCH
GO
EXEC Snapshot_HistoryTable 12356,'2019-09-22 00:00:00'