I have this SQL Server Agent, that creates a backup table, doing this:
DECLARE @date datetime, @insert_cmd varchar(1000)
SET @date =GETDATE()
set @insert_cmd = 'select * into [tablename_'+CONVERT(varchar(100), @date, 112 )+'] from tableA'
exec (@insert_cmd)
Trouble is, select * into table only works if table doesn’t exist already. Is there a way to change this to insert into tablename_…. without caring, and just overwrite if necessary?
I’ve tried looking at using sql to check if the table exists, doing something like:
IF OBJECT_ID ('tablename', 'U') IS NOT NULL DROP tablename;
The trouble with that is how to do i situate those quotes so they work to build the date/time added to the table name? I’ve tried a few variations, but none have panned out:
/* errors with quotations: */
set @del_cmd = 'IF OBJECT_ID ('[tablename_'+CONVERT(varchar(100), @date, 112 )+']', 'U') IS NOT NULL DROP [tablename_'+CONVERT(varchar(100), @date, 112 )+']';
Full credit to @aaronBertrand, Here’s the code i ended up with:
Big thank you!