我有一个进入"db_owner"模式的表,我需要它在"dbo"模式中.
是否有运行的脚本或命令来切换它?
ALTER SCHEMA [NewSchema] TRANSFER [OldSchema].[Table1]
在SQL Server Management Studio中:
右键单击表并选择修改(现在称为"设计")
在属性面板上,选择正确的拥有架构.
TABLE_SCHEMA
通过此选择显示全部:
SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
您可以使用此查询将所有表的所有架构更改为dbo表架构:
DECLARE cursore CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA <> 'dbo' DECLARE @schema sysname, @tab sysname, @sql varchar(500) OPEN cursore FETCH NEXT FROM cursore INTO @schema, @tab WHILE @@FETCH_STATUS = 0 BEGIN SET @sql = 'ALTER SCHEMA dbo TRANSFER ' + @schema + '.' + @tab PRINT @sql FETCH NEXT FROM cursore INTO @schema, @tab END CLOSE cursore DEALLOCATE cursore
简单的答案
sp_changeobjectowner [ @objname = ] 'object' , [ @newowner = ] 'owner'
您不需要停止与数据库的所有连接,这可以在运行中完成.
一个微小的改进赛义德的出色答卷......
我添加了一个exec来让这个代码自行执行,我在顶部添加了一个union,这样我就可以更改表和存储过程的模式:
DECLARE cursore CURSOR FOR select specific_schema as 'schema', specific_name AS 'name' FROM INFORMATION_SCHEMA.routines WHERE specific_schema <> 'dbo' UNION ALL SELECT TABLE_SCHEMA AS 'schema', TABLE_NAME AS 'name' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA <> 'dbo' DECLARE @schema sysname, @tab sysname, @sql varchar(500) OPEN cursore FETCH NEXT FROM cursore INTO @schema, @tab WHILE @@FETCH_STATUS = 0 BEGIN SET @sql = 'ALTER SCHEMA dbo TRANSFER [' + @schema + '].[' + @tab +']' PRINT @sql exec (@sql) FETCH NEXT FROM cursore INTO @schema, @tab END CLOSE cursore DEALLOCATE cursore
我也不得不恢复dbdump,并发现架构不是dbo - 我花了好几个小时试图让Sql Server管理工作室或visual studio数据传输来改变目标架构......我最后只是针对恢复运行这个在新服务器上转储以获得我想要的方式.