P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

SQL - Programmatically rename all table columns in a database

Say I have a table: UltimateTable. It has columns: UltimateColumn1, UltimateColumn2. They should be renamed

UltimateTable_UltimateColumn1
UltimateTable_UltimateColumn2

I believe I can iterate tables with sp_MSForEachTable. How can I rename all the tables in a single database per the example with T-SQL?

I know a lot of people are not a fan of appending table names to column names when an alias will do. Get over it. It's the company standard.

(j/k I hate it too...)

Upvotes: 0

Views: 1658

Answers (1)

anon
anon

Reputation:

I agree with Mitch that this is a seriously bad idea and you should fight it to the death. That said, there are easy ways to generate this type of script using the catalog views (not sp_MSForEachTable, which still only gets you the table names, not the column names, anyway).

Run this in one window:

SELECT 'EXEC sp_rename ''' + QUOTENAME(TABLE_SCHEMA) 
  + '.' + QUOTENAME(TABLE_NAME) + '.' 
  + QUOTENAME(COLUMN_NAME) + ''', ''' 
  + TABLE_NAME + '_' + COLUMN_NAME + ''', ''COLUMN'';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME NOT LIKE TABLE_NAME + '[_]%';

Now copy and paste the output into a new window. Check it over before executing - and test it on a test database first!

Upvotes: 3

Related Questions