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 55
Scott Fell,  EE MVEDeveloper & EE ModeratorAsked:
Who is Participating?
 
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
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Scott Fell, EE MVEDeveloper & EE ModeratorAuthor Commented:
Thank you.  What about the find and replace for the table names in views and stored procedures?
0
 
mimran18Commented:
0
 
Scott Fell, EE MVEDeveloper & EE ModeratorAuthor 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.