开发者

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

UltimateT开发者_Python百科able_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...)


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜