还记得多年前,有个客户要求把本来默认属于dbo架构的数据库表全部修改为其他自定义的架构。那时,对数据库不熟,为了那100多张表还折腾了很久才弄好。其实是一个很简单的问题,现在就当作笔记记录一下吧。修改下面相应对象的类型,可以批量修改表、视图、函数、存储过程等对象的架构。
--批量修改表架构名 DECLARE @sql_text NVARCHAR(MAX); SET @sql_text = ''; BEGIN TRY BEGIN TRAN SELECT @sql_text = @sql_text + N'ALTER SCHEMA ' + N'新架构名' + N' TRANSFER [' + s.name + '].[' + p.name + '];' + CHAR(13) FROM sys.objects p INNER JOIN sys.schemas s on p.schema_id = s.schema_id WHERE p.[type] = 'U' AND s.name = N'旧架构名' ORDER BY P.name ASC; --PRINT @sql_text IF @sql_text = '' BEGIN RAISERROR('No records have been changed!',16,1); END ELSE BEGIN EXEC (@sql_text); END; COMMIT TRAN; END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; ROLLBACK TRAN; END CATCH; GO
code-1:批量修改表的架构