我需要重命名数据库中所有表中的列。 所以一个专栏' OldColumn'必须重命名为“NewColumn'在所有表中
我可以使用此查询获取包含此列的表的列表:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME= <Column Name>
但是如何在所有表格中尽可能简单地重命名并且不必编写游标?
答案 0 :(得分:5)
当然,你不需要光标。您可以使用sys.columns和sys.objects生成动态sql。然后简单地执行它。一旦您满意,动态SQL就是您想要取消注释最后一行的内容。
----警告!!!! ---- 如果更改列名,您的视图,存储过程,函数等都将被破坏。
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
答案 1 :(得分:1)
请尝试这个,这将生成脚本
select 'EXEC sp_rename ' + tableName + ''' OldColumn''' + ' ' + '''NewColumn'''
from
(select distinct OBJECT_NAME(OBJECT_ID) tableName from sys.columns where name like '%DUNS%')a
答案 2 :(得分:0)
您可以生成这样的脚本,然后一次执行:
declare @oldColumn nvarchar(max) = 'department_id'
declare @newColumn varchar(max) = 'dept_id'
declare @query nvarchar(max)
select 'exec sp_rename '+ char(39) + table_name + '.' + @oldColumn + char(39)
+', '+ char(39) + @newColumn + char(39) + ','+ char(39) + 'COLUMN' +Char(39) + ' GO ' from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME = 'department_id'
生成的脚本供您参考:
exec sp_rename 'table5.department_id', 'dept_id','COLUMN'
exec sp_rename 'table6.department_id', 'dept_id','COLUMN'
exec sp_rename 'table1.department_id', 'dept_id','COLUMN'
答案 3 :(得分:0)
下面动态地获取DB中包含给定列名的所有表名,在本例中为“COL_A”,并将这些名称插入表中,在本例中为“DBO.QUEUE”。然后该表充当下面光标的队列。动态SQL用于遍历队列并调用sp_RENAME重命名每个适用表中的列。
--The below two tables will be found and update
CREATE TABLE DBO.TEST1 (COL_A INT)
CREATE TABLE DBO.TEST2 (COL_A INT)
--The below will NOT update
CREATE TABLE DBO.TEST3 (COL_B INT)
--Create a table to act as a queue
CREATE TABLE DBO.QUEUE (TABLENAME VARCHAR(255))
--Insert into the queue based upon your criteria
INSERT INTO QUEUE
SELECT DISTINCT(TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME= 'COL_A'
--Run the cursor to update
DECLARE
@TABLENAME VARCHAR(255)
DECLARE Cursor_Name CURSOR LOCAL FAST_FORWARD FOR
SELECT
TABLENAME
FROM
DBO.QUEUE AS LIST;
OPEN Cursor_Name
FETCH NEXT FROM Cursor_Name INTO @TABLENAME
WHILE @@FETCH_STATUS = 0
BEGIN
--Dynamic SQL is used to execute the sp_Rename procedure with the applicable table name.
Declare @colupdate_ varchar(MAX)
set @colupdate_=
'EXEC sp_RENAME ' + '"' + @TABLENAME + '.' + 'COL_A' + '"' + ',' + '"' + 'NEW_COLUMN_NAME' + '"' + ',' + '"' +'COLUMN' + '"'
exec(@colupdate_)
FETCH NEXT FROM Cursor_Name INTO @TABLENAME
END
CLOSE Cursor_Name
DEALLOCATE Cursor_Name