Kumar
Kumar

Reputation: 11349

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.

Upvotes: 6

Views: 1167

Answers (4)

bugfixr
bugfixr

Reputation: 8077

Can you use this?

sp_RENAME 'Table.ColumnName%', 'NewColumnName' , 'COLUMN'

Upvotes: 5

Cade Roux
Cade Roux

Reputation: 89671

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

Upvotes: 8

SQLMenace
SQLMenace

Reputation: 135021

here is an example that will loop over a table and change underscores and percent signs

create table Test ([col%1] varchar(50),[col_2] varchar(40))
go

select identity(int,1,1) as id ,column_name,table_name into #loop
 from information_schema.columns
where table_name = 'Test'
and column_name like '%[%]%'
or column_name like '%[_]%'


declare @maxID int, @loopid int
select @loopid =1
select @maxID = max(id) from #loop

declare  @columnName varchar(100), @tableName varchar(100)
declare  @TableColumnNAme varchar(100)
while @loopid <= @maxID
begin


select @tableName = table_name , @columnName = column_name
from #loop where id = @loopid

select @TableColumnNAme = @tableName + '.' + @columnName
select @columnName = replace(replace(@columnName,'%',''),'_','')
EXEC sp_rename @TableColumnNAme, @columnName, 'COLUMN';

set @loopid = @loopid + 1
end

drop table #loop

select * from Test

Upvotes: 3

gbn
gbn

Reputation: 432301

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'

Upvotes: 9

Related Questions