简体   繁体   中英

sql rename all column names given a string with new column names

I would like to rename all column names of a table given a string with new names separated by comma. Here be the string:

declare @str varchar(max)='A,B,C'

The number of columns in a table may vary, and appropriately the number of names in a string. So in a 5-column table the string would be 'A,B,C,D,E' .

I have a table with column names as:

col1 | col2 | col3

and in expected results I would like to have:

A | B | C

Update I have tried to follow that path:

SELECT 
 ORDINAL_POSITION
,COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE 
TABLE_NAME = 'my_temp'
order by ORDINAL_POSITION asc

but I do not know how to split @sql string so that it can be applied to results in the following way:

ORDINAL_POSITION  COLUMN_NAME  sql_string  
1                 Col1         A  
2                 Col2         B  
3                 Col3         C   

Then I could easily create a string like:

dynamic_sql='EXEC sp_rename my_table.' + COLUMN_NAME +',' + sql_string +', ''COLUMN'''

Using the splitter from Jeff Moden I have referenced in the comments here and the answer on your question you can do this easily. http://www.sqlservercentral.com/articles/Tally+Table/72993/

Here is a full working example. It would be really helpful if you could post sample tables in your questions so we don't have to do that to work on the questions.

if object_id('SomeTable') is not null
    drop table SomeTable

create table SomeTable
(
    Col1 int
    , Col2 int
    , Col3 int
)

--to demonstrate the column names before we change them
select * from SomeTable

declare @NewNames varchar(100) = 'A,B,C'
    , @SQL nvarchar(max) = ''

select @SQL = @SQL + 'EXEC sp_rename ''SomeTable.' + c.name + ''', ''' + s.Item +''', ''COLUMN'';'
from sys.columns c
join dbo.DelimitedSplit8K(@NewNames, ',') s on s.ItemNumber = c.column_id
where object_id = object_id('SomeTable')


select @SQL
--exec sp_executesql @SQL

--demonstrates the column names have been changed.
select * from SomeTable

I have said this previously and I can't in good conscience not mention it again. The fact that you need to do this is a huge red flag that there is something very very wrong with the way you managing your data. Changing column names should not happen very often at all and only when absolutely required. Doing this routinely is a sign that there are really big issues with the process or the design.

This would give you the names of all the columns of an existing table in the correct order

select c.name
  from sys.columns c
    inner join sys.objects o on c.object_id = o.object_id 
 where o.name = 'name_of_table'
 order by c.column_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM