Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

sql server - rename a column in all the tables - SQL

I need to rename a column in all tables in my database. so a column 'OldColumn' has to be renamed to 'NewColumn' in all the tables

I could get list of tables that has this column using this query:

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE COLUMN_NAME= <Column Name>

But how can i rename it in all tables as simple as possible and don't have to write a cursor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Of course you don't need a cursor for this. You can use sys.columns and sys.objects to generate dynamic sql. Then simply execute it. Once you are satisfied the dynamic sql is what you want feel free to uncomment the last line.

----BE WARNED!!!!---- If you change column names your views, stored procedures, functions etc will all be broken.

declare @CurrentColumnName sysname = 'asdf'
    , @NewColumnName sysname = 'qwer'
    , @SQL nvarchar(MAX) = ''

select @SQL = @SQL + 'EXEC sp_rename ''' + o.name + '.' + c.name + ''', ''' + @NewColumnName + ''', ''COLUMN'';'
from sys.columns c
join sys.objects o on o.object_id = c.object_id
where c.name = @CurrentColumnName

select @SQL

--exec sp_executesql @sql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...