Removing spaces in column names RRS feed

  • Question

  • Hi

    I have imported a number of tables from a legacy db. The column names in tables have spaces in them. Is there a script I can run to remove spaces from column names in all tables?


    Monday, February 3, 2014 2:20 AM


  • First of all, I do not agree with the concept of changing the column names. There is a good chance of breaking your code, if the table has been referred in procs/functions etc.

    One good method would be, import the tables from legacy db into staging and then insert into your actual tables by mapping the tables correctly where your actual table would not have the [space].[Here, I assume your procs/functions etc refer only your actual tables not staging tables].

    OR, if you are looking for a plain logic, then use the below:

    The below script wont execute the change, but just would give the statements to be executed to make the column modifications. This is intentional, because this is not a good practice and you can verify the objects and scripts rather than executing it directly.

    create table test_table([column test space] int) --select * From test_table --Script to do the change in column name select 'EXEC sp_rename '''+ B.name+'.'+a.name +''', '''

    +replace(a.name,' ','') +''', ''COLUMN'''

    from sys.columns A Inner join sys.tables B on A.object_id = B.object_id and

    OBJECTPROPERTY(b.object_id, N'IsUserTable') = 1 where system_type_id in (select system_type_id From sys.types ) and charindex(' ',a.name)<>0 /* EXEC sp_rename 'tbl_apas_t_tech.application id', 'applicationid', 'COLUMN' EXEC sp_rename 'test_table.column test space', 'columntestspace', 'COLUMN' */ Drop table test_table

    EDIT: Formatting...

    Monday, February 3, 2014 2:56 AM