Uncategorized

Backup single table with timestamp

A simple script to create a backup of a given table in this format:

SELECT * INTO [dbo].[SampleTable_20220803103001] FROM [dbo].[SampleTable];
DECLARE @TimeStamp NVARCHAR(MAX)
DECLARE @Stmt NVARCHAR(MAX)
DECLARE @SchemaName NVARCHAR(128)
DECLARE @TableName NVARCHAR(128)

SET @SchemaName = 'dbo'
SET @TableName = 'SampleTable'

SET @TimeStamp = FORMAT(GETDATE(), 'yyyyMMddHHmmss')

SET @Stmt = N'SELECT * INTO [' + @SchemaName + '].[' + @TableName + '_' + @TimeStamp + '] FROM [' + @SchemaName + '].[' + @TableName + '];'
 
PRINT @Stmt
EXECUTE(@Stmt)
GO