Mass rename SQL tables

I have inherited a db with tables named like

dbo.xyz_aaaa
dbo.xyz_bbb
dbo.abc_cccc
dbo.abc_dddd
dbo.eeee
dbo.ffff

Everything to the right of the underscore is unique and I want to end up with

dbo.aaaa
dbo.bbb
dbo.cccc
dbo.dddd
dbo.eeee
dbo.ffff

Is there a way to use sql server to mass update dbo.xyz_aaaa to dbo.aaaa including any  Views or Stored procedures.   Or do I just use the generate scripts function, use the editor to do to a find and replace, then recreate?
LVL 54
Scott Fell,  EE MVEDeveloperAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
mimran18Connect With a Mentor Commented:
Select * from syscomments Where [text] like '%tablename%'
0
 
BlueYonderConnect With a Mentor Commented:
A script is possible. Use the following for the table names and a cursor to traverse the each table.

SELECT name
FROM dbo.sysobjects
WHERE xtype = 'U' AND --THE NAME OF THE DB--



ALTER TABLE table_name
RENAME TO new_table_name;
0
 
mimran18Connect With a Mentor Commented:
TRY THIS

SELECT 'ALTER TABLE ' + NAME +  ' RENAME TO ' + Substring(name ,CharIndex('_',name)+1,LEN(name))
FROM dbo.sysobjects
WHERE xtype = 'U' And CharIndex('_',name)>0
0
Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

 
Scott Fell, EE MVEDeveloperAuthor Commented:
Thank you.  What about the find and replace for the table names in views and stored procedures?
0
 
mimran18Commented:
0
 
Scott Fell, EE MVEDeveloperAuthor Commented:
Thanks, I got it done.  For the views and stored procs I just generated the script and did a find and replace.
0
 
mimran18Commented:
You are Welcome
0
All Courses

From novice to tech pro — start learning today.