views:

110

answers:

4

I have a table with 600+ columns imported from a csv 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.

+4  A: 

Can you use this?

sp_RENAME 'Table.ColumnName%', 'NewColumnName' , 'COLUMN'
Chu
+8  A: 

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'
gbn
+6  A: 

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

Cade Roux
+3  A: 

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
SQLMenace