Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create a Variable Table name?? 2

Status
Not open for further replies.

tEkHEd

IS-IT--Management
Jan 29, 2003
261
GB
Hi I want to be able to keep historic data, and need to archive tables.

to do this I want the table to have some form of datestamp, I have decided that I want to use the Julian Date (Day of Year) as the suffix.

I have managed to create the dynamic table name, but cannot seem to use a variable for this table name in an SELECT -- INTO statement.. :¬?

Can anyone tell me why this syntax does not work??
Code:
DECLARE @DOY AS CHAR(3), @TBLPREF AS CHAR(14), @TBLNAME AS CHAR(19)
-- Retrieves the Day of the Year (Julian Date)
SET @DOY = (SELECT DATENAME(dy, GETDATE()))
SET @TBLPREF = 'dbo.tblArchive'
SET @TBLNAME = @TBLPREF+@DOY

print @tblname -- prints the correct table name of dbo.tblArchiveXXX where XXX is Julian Date

SELECT *
INTO @TBLNAME -- Incorrect syntax here...
from tblSource

Do I have to use a different query for this? Is there a Rename command that I could use instead?

Thanks in adv
 
You cannot use variables in place of object names. You must use dynamic SQL here:

Code:
DECLARE @sql varchar(200)
SET @sql = 'SELECT * INTO ' + @tblname + ' FROM tblsource'
EXEC(@sql)

--James
 
Hehe.. so simple.. really should have thought about that.. thanks for waking me up James :D
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top