Question

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 )+']'; 
Was it helpful?

Solution

Full credit to @aaronBertrand, Here's the code i ended up with:

DECLARE @insert_cmd varchar(MAX), @del_cmd NVARCHAR(MAX), @date datetime
SET @date =GETDATE()
  IF OBJECT_ID('tablename_' + CONVERT(varchar(100), @date, 112 ) ) IS NOT NULL 
   BEGIN 
SET @del_cmd = N'DROP TABLE tablename_' + CONVERT(varchar(100), @date, 112 ); 
EXEC sp_executesql @del_cmd; 
   END
SET @insert_cmd = 'select * into tablename_'+CONVERT(varchar(100), @date, 112 )+'] from TableA'
EXEC (@insert_cmd)

Big thank you!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top