Link to home
Start Free TrialLog in
Avatar of HNA071252
HNA071252Flag for United States of America

asked on

SQL - concatenated table name

In this statement, I have to manually change the date of the table name everytime when I want to run this code:

 
SELECT *
INTO TRP.Cap_Data_20111007
FROM TRP.Cap_Data

Instead of manually changing it, can I do something like this?

DECLARE @yyyymmdd nvarchar(8)
SET @yyyymmdd = convert(varchar(8),getdate(),112)
 
SELECT *
INTO TRP.Cap_Data_ & '@yyyymmdd'
FROM TRP.Cap_Data

I'm not sure if there's a way to do this, but I'm not able to figure out how to. Please help.
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

yes, dynamic sql would be the way
DECLARE @yyyymmdd nvarchar(8)
SET @yyyymmdd = convert(varchar(8),getdate(),112) 

DECLARE @SQL nvarchar(1000)

SET @SQL = ' SELECT * 
INTO TRP.Cap_Data_' + @yyyymmdd + '
FROM TRP.Cap_Data '
exec(@sql)

Open in new window

Avatar of HNA071252

ASKER

That's awesome! One more thing, what do I do if I need to add the time to the end of the table name?

i.e. 20111007_1525
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you very much!