Sunday, February 5, 2012

Rename Schema in MS SQL Server

My requirement is to rename the schema in selected tables/views.
Let take a example like this.
Existing table name - HRADMIN.VW_HR_EMPLOYEE
Required table name - HRUSR. VW_HR_EMPLOYEE

You can simply do this by using below SQL command by login with sa account. Make sure your rename schema is exists under your Data Base. Otherwise you need to create it manually.

ALTER SCHEMA <HRUSR> TRANSFER  <HRADMIN>.< VW_HR_EMPLOYEE >

But it's not flexible enough  when we are considering the large database which consisted lot of tables/views under same schema. The below Stored Procedure will help you to generate one script for entire schema which you want to rename.

<Views/tables which exists under ADM schema will rename the schema of CHATHURA >


ALTER PROCEDURE SP_CHANGE_SCHEMA
AS
DECLARE cursore CURSOR FOR
SELECT TABLE_SCHEMA, TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA  =  'ADM'

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 CHATHURA TRANSFER ' + @schema + '.' + @tab  
 PRINT @sql  
 FETCH NEXT FROM cursore INTO @schema, @tab  
END

CLOSE cursore  
DEALLOCATE cursore

After creating the SP you can execute it by using this command.

EXEC SP_CHANGE_SCHEMA

1 comment: