sql-make a tablename string that includes getdate

66 Views Asked by At

I'm tryin to do this:

select * into 'DataBackup'+convert(varchar(10),getdate(),112)+'byMike' from SomeTable 

but it returns an error. I also tried this one but to no avail:

select * into
(select 'DataBackup'+convert(varchar(10),getdate(),112)+'byMike') 
from
SinavSorulari

Basically, I'm trying to make a string that reads: DataBackup20161230byMike and I want to use it with `SELECT * INTO. Can I do that?

Thanks.

2

There are 2 best solutions below

0
On BEST ANSWER

Try this:

declare @query varchar(max)
set @query='select * into DataBackup'+convert(varchar(10),getdate(),112)+'byMike from some_table '
exec ( @query)
0
On
declare @tablename = 'DatabaseBackup'+convert(varchar(10),getdate(),112)+'byMike'

declare @yoursourcetable = 'Mytable'

declare @selectsql
set @selectsql='select * into '+ @tablename +' from '+@yoursourcetable

sp_executesql ( @selectsql )

I haven't tested it, but should work