2

I have a database say test in SQLServer 2008 which have almost more than 100 tables inside it . I have requirement that I have to add prefix to these tables .

for e.g. table employee should be renamed as companyName_employee . companyName_ is the prefix I want to apply.So table department should be renamed to companyName_department

Currently I can rename tables one by one by running below query :

sp_rename employee, companyName_employee

sp_rename only renames one table at a time.

I am new to SQLServer so please suggest if there is a way to rename multiple tables in one query

1
  • Do you need to preserve the data? What performance requirements are there? Commented Oct 1, 2014 at 10:47

1 Answer 1

5

You can generate the sp_rename statements using dynamic sql. Like this:

SELECT 'exec sp_rename ''' + name + ''', ''companyName_' + name + ''''
FROM sysObjects
WHERE type = 'U'
Sign up to request clarification or add additional context in comments.

3 Comments

and how to run this dynamic SQL ... because When I run this query it is giving result as exec sp_rename 'qualityrating', ' companyName_qualityrating' but It does actually renames the tables . how to run this statement ?
Copy all the statements, then execute them by hand. This query only generates the queries, it will not execute them.
@Shree It is possible to generate the update statements and execute them at once - but this would require cursors and is a lot more involved. Probably not worth it for a once off table rename like this. As Pred said - with this answer you can generate the statements, copy and run them manually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.