Search code examples
sqlsql-serverssmssql-server-2019

Writing an Script That Makes Alter Query For Target Objects in SQL Server 2019


I have a List Of Columns Which Started With Lower case Letters . this List Have 270 Record , It means That I have 270 Column Name in Data Base that Should Rename To start with Upper Case Letter . I Have the List With This Script :

select * from information_schema.columns where ascii(left(column_name, 1)) between ascii('a') and ascii('z');

I want a Query To Generate Alter Scripts For Each Record Of my Select Statement In a Format Like :

ALTER TABLE [TableName] RENAME COLUMN [OldColumnName] TO [NewColumnName];

or Like This One :

ALTER TABLE TableName CHANGE COLUMN OldColumnName NewColumnName Data Type;

The old [Old_Column_Name] Start With Lower Case Letter, so the [New_Column_Name] Should Start With Upper Case Letter .

for Example : old Name = user ===> New Name = User

Thanks.


Solution

  • While it's still not entirely clear to me what you are looking for, and whether this will actually change the case names in your database (settings vary), the following should work:

    select 'EXEC sp_rename '''+TABLE_SCHEMA+'.'+TABLE_NAME+'.'+COLUMN_NAME+''', '''
        +CHAR( ASCII(LEFT(COLUMN_NAME,1))-32 ) + SUBSTRING(COLUMN_NAME,2,LEN(COLUMN_NAME))
        +''', ''COLUMN'';  '
    from information_schema.columns where ascii(left(column_name, 1)) between ascii('a') and ascii('z');