Saturday, December 21, 2013

Change schema name of tables, store procedure, views and functions

Today i come across one situation where i need to changes my current SQL schema to some other name. due to client requirement.so i searched few article and decided to write one article on same

Below query will returns list of all tables along with the schema name from your database.



SELECT TABLE_SCHEMA, TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES


If you want to add new schema you need to add that into sys.schemas table then only it will be accessible else it will give an error message as 


 Cannot alter the schema 'xxx', because it does not exist or you do not have permission.
 

IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'Excprod'))
BEGIN
    EXEC ('CREATE SCHEMA [Excprod] AUTHORIZATION [dbo]')
END

You can also view list of schema from below query and you will find new schema "Excprod" get added.

SELECT * FROM sys.schemas

Now, below query used to alter the scheme tables

ALTER SCHEMA Excprod TRANSFER dbo.Temp1
ALTER SCHEMA Excprod TRANSFER dbo.Temp2
ALTER SCHEMA Excprod TRANSFER dbo.temp3


You may also alter the schema for store procedure as well. to find the list of all store procedures from your
database just use.



select * from information_schema.routines
where routine_type = 'PROCEDURE'


below query will generate the select statement for all list of sp



select 'ALTER SCHEMA Excprod TRANSFER ' + SPECIFIC_SCHEMA + '.' + ROUTINE_NAME
from INFORMATION_SCHEMA.ROUTINES where ROUTINE_TYPE='procedure'
Result will be :


ALTER SCHEMA Excprod TRANSFER synprod.Usp_Response
ALTER SCHEMA Excprod TRANSFER synprod.Usp_Request


To view list of view from database use this


SELECT * FROM information_schema.VIEWS


Please comment if you want more details on this.

No comments:

Post a Comment