Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


Rename table using dynamic SQL

Posted on 2005-02-25
Medium Priority
Last Modified: 2012-06-21
I would like to rename a table by appending the current date to the front of a table name.
For example:

Rename this table: Table1
To: 02212005_Table1 (month, day, year)

How can I perform this using dynamic SQL or by using sp_rename?

Thanks in advance . . .

Question by:rikroket
  • 3
  • 2
LVL 13

Expert Comment

ID: 13407741
declare @newname varchar(20)
set @newname =  convert(varchar(2), day(GetDate()) ) + convert( VARCHAR(2) , MONTH(GETdATE()))
               + convert(char(4), Year(getdate()))

set @newname  = @newname + '_abc'
exec sp_rename 'Table1', @newname
LVL 21

Accepted Solution

Kevin3NF earned 2000 total points
ID: 13407772

Declare @NewName varchar(100)
Set @NewName = cast(datepart(mm,getdate())as varchar(2))
                +cast(datepart(dd,getdate())as varchar(2))
                +cast(datepart(yyyy,getdate())as varchar(4))

Select @NewName = @NewName + '_Test'

exec sp_rename 'Test',@NewName
LVL 21

Expert Comment

ID: 13407783
Missed it by > that< much....well done KarinLoos
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

LVL 43

Expert Comment

by:Eugene Z
ID: 13408142
LVL 43

Expert Comment

by:Eugene Z
ID: 13408143
ops - wrong post
LVL 21

Expert Comment

ID: 13408314
Hey rikroket....as much as I appreciate the points....I was second with the answer. :-)

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Suggested Courses

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question