开发者

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.


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'


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


Can you use this?

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


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜