views:

246

answers:

4

I have a database where all of the tables are prefixed with a set of the same characters. This was done because at one time they were in a shared database set up for pet projects with hundreds of other tables. The application, and thus the database, is now ready to be moved out of that phase and ready to be out on it's own. I would like to remove the prefix for each of the tables. Is there an easier way to do this rather than right-clicking and renaming each table individually?

+4  A: 

You could write a script to look at the meta information and change it, but won't this ruin all your SPs and Parameterized Queries?

Hogan
It'll ruin everything - views, etc. If there's SCHEMABINDING on anything, that'll have to be dealt with first...
OMG Ponies
+2  A: 

You could do something like script the whole database and do string replacement on the script, run it on a new database, and then import the data. This of course depends on how well you can match the string to be replaced. You might have to make corresponding changes in your application too. You could always try something like this on a test database to see if it would work.

Take a look at this too - Mass Renaming of Tables and Stored Procedures

One method has some cost and the other is similar to my suggestion.

Bratch
@Bratch +1 a much nicer way of saying what I said.
Hogan
@Hogan Yeah, but different. Your answer sounds more like actually writing a script to modify the meta data. I'm not saying you need to write a script at all, just script out the database as SQL commands (Right-click, Tasks, Generate Scripts). Do a find/replace and replace the prefix with nothing, and then run the modified SQL on the new database. This will rename all references to the tables in the views and sprocs too. A quick look at the SQL generated by the db script should give an idea if it will work right or not.
Bratch
A: 

First, write a stored procedure that has a table name parameter and uses string parsing and ALTER TABLE to remove the prefix from the specified table.

Then, use sp_MSforeachtable to call that procedure for each table.

Reference: http://weblogs.sqlteam.com/joew/archive/2007/10/23/60383.aspx

Josh Yeager
+1  A: 
select 'exec sp_rename @objname=' + name + ', @newname=' + replace(name ,'prefixedchars', '')
from sysObjects
where type = 'U'

The results from this will be something like:

exec sp_rename @objname=prefixedcharsTable1, @newname=Table1
exec sp_rename @objname=prefixedcharsTable2, @newname=Table2
exec sp_rename @objname=prefixedcharsTable3, @newname=Table3
etc... for each table in your db

All you have to do is copy those statements into a new query window and run.

Caveats:

  • You will get an cautionary message as follows: Caution: Changing any part of an object name could break scripts and stored procedures.
  • You will have to rename the tables in any stored procedures, functions, views, and triggers.
Jason