Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 How can i rename a table using SQL

Author  Topic 

NgKH
Starting Member

15 Posts

Posted - 2003-05-26 : 10:14:01
given i have got a table named f_policy
i wanted to rename that table into
@month_f_policy where @month is the current month. so this month would be 05_f_policy and december would be 12_f_policy

how can i able to do that in SQL?


JCamburn
Starting Member

31 Posts

Posted - 2003-05-26 : 11:09:20
I would not use a number for the name of a table in SQL server. I have seen a bug involved with doing this.

The following code will give you table names like Jan_f_policy, Feb_f_policy.

You will need to replace "DateColumn" in the code below with whatever your own column name is. You may also need to modify '1/1/2003' depending upon the dates you are working with. NOTE: If f_policy contains more than a year's worth of data, this will put all data from January into the first table regardless of which year it is in. You may also have to make modifications if you are not using SQL 2000. Let me know if you have any questions.


DECLARE @intMonth integer
DECLARE @vchSQL varchar(2000)
DECLARE @vchMonth varchar(3)

SET @intMonth = 1
SET @vchMonth = DATENAME(mm, DATEADD(mm, @intMonth - 1, '1/1/2003'))

WHILE (@intMonth < 13)
BEGIN
SET @vchSQL = 'SELECT * INTO ' + @vchMonth + '_f_policy FROM f_policy WHERE MONTH(DateColumn) = ' + CAST(@intMonth AS varchar(2))
EXECUTE (@vchSQL)
SET @intMonth = @intMonth + 1
SET @vchMonth = DATENAME(mm, DATEADD(mm, @intMonth - 1, '1/1/2003'))
END


Go to Top of Page

Merkin
Funky Drop Bear Fearing SQL Dude!

4970 Posts

Posted - 2003-05-26 : 20:55:49
I would look very closely at your database design and question it.

If you are creating a table for each month, you are breaking all sorts of rules about good design. A better scenario would be one table with a date or month column.


Damian
Go to Top of Page
   

- Advertisement -