Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Change SQL Server column names in T-SQL?

I have a table with 600+ columns imported from a CSV file with special chars % _ - in the column names. Is there a way to change the column names to remove these special chars?

The code can be in T-SQL.

like image 885
Kumar Avatar asked May 27 '10 14:05

Kumar


People also ask

How do I rename a column in SQL query?

To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.


2 Answers

sp_rename?

EXEC sp_rename 'table.[Oh%Dear]', 'OhDear', 'COLUMN';

Worked example (was not sure about [ ] in sp_rename)

CREATE TABLE foo ([Oh%Dear] int)

EXEC sp_rename 'foo.[Oh%Dear]', 'OhDear', 'COLUMN'

EXEC sys.sp_help 'foo'
like image 190
gbn Avatar answered Sep 26 '22 14:09

gbn


You can query INFORMATION_SCHEMA.COLUMNS and generate sp_rename scripts to rename the columns.

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

Here's a permalink to an actual runnable example

like image 40
Cade Roux Avatar answered Sep 24 '22 14:09

Cade Roux