views:

213

answers:

4

Hello all.

I understand that I can change a sql table using the follow sp:

EXEC sp_rename 'customers', 'custs'

How would I go about appending this so that the new table has today's date as a suffix?

I've attempt variations on the below theme with little success!!

EXEC sp_rename 'customers', 'customers +(CONVERT(VARCHAR(8),GETDATE(),3))'

Any help greatly appreciated.

+1  A: 
DECLARE @TableName varchar(50)

SELECT @TableName = (SELECT 'Customers_' + convert(varchar(50),GetDate(),112))

EXEC sp_rename 'customers', @TableName
JonH
I can't answer with a tick yet but that's spot on Jon..thank you very much.
Ricardo Deano
@Ricardo Deano - No problem make sure you accept the answer if it works.
JonH
+1  A: 

You mean T-SQL, right? Move the functions outside of the single quotes. Something like:

EXEC sp_rename 'customers', 'customers' +(CONVERT(VARCHAR(8),GETDATE(),3))
Dan Diplo
+4  A: 

This sounds like a very bad thing to do! you should evaluate your design, renaming your tables with dates in the names suggests that you will be spawning many tables, each for a different date. You could possibly add a date column into your table and use that to differentiate the data instead of creating completely new tables for different dates.

With that said, you can not have an expression as a parameter to a stored procedure in SQL Server. By attempting to concatenate the formatted date to the string 'customers', you were trying to pass an expression as a parameter.

you must store the expression in a local variable first, and then call the stored procedure with that local variable:

DECLARE @Value varchar(500)
SET @Value='customers' +(CONVERT(VARCHAR(8),GETDATE(),3))
EXEC sp_rename 'customers', @Value
KM
I'd upvote you a million times if I could, this is generally a really really bad choice.
HLGEM
Thanks for the advice KM, taken note of and I will most likely modify the design and implement something along the lines of what you have suggested i.e. an in table date stamp.My one concern with this is that this table will get big...very very big. In addition to this, my LINQ to SQL will have to be modified and I'm not sure at present how I can amend this so that only the latest 'customer' is taken i.e. based upon the date stamp.Hmmm...food for thought. You may see a few more questions coming soon!!
Ricardo Deano
A: 

Since you should almost never do this on such a regular basis that you need to figure out the date programmically, I suggest this for the occasional use:

EXEC sp_rename 'customers', 'customers20100408' 
HLGEM
if you were going to recommend a date format, why not YYYYMMDD: `customers20100408`?
KM
@KM, I fixed it, you are right the unambiguous date is better.
HLGEM