Uncategorized

Backup single table with timestamp

Simple script to create backup of given table in this format:

SELECT * INTO [dbo].[SampleTable_20180820152224] 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