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.
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.
Can you use this?
sp_RENAME 'Table.ColumnName%', 'NewColumnName' , 'COLUMN'
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 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