SQL Server ALTER SCHEMA Introduction
In our previous tutorial, you have learned what a SCHEMA in SQL Server and how to create aSQL Server SCHEMA
. Also, you have learned how to create objects inside a schema.
Sometimes a situation arises like to transfer an already created object to another schema within the same database.
The SQL Server ALTER SCHEMA statement allows you to transfer the ownership of objects to another schema with in the same database.
In the subsequent sections, you are going to learn the syntax and example of SQL Server ALTER SCHEMA.
ALTER SCHEMA Syntax
The following shows the syntax of ALTER SCHEMA statement in SQL Server.ALTER SCHEMA target_schema_name TRANSFER [ entity_type :: ] object_name;In this syntax,
- ALTER SCHEMA – The keyword used for transferring the ownership of objects from one schema to another.
- target_schema_name – The name of the target schema within same database where you want to move the object. Note that you can move any objects in SYS and INFORMATION schema.
- TRANSFER – Keyword.
- entity_type – This can be an Object, Type or XML schema collection. This defines the class of the entity for which the ownership is being changed.
- object_name – The name of the object you want to move.
ALTER SCHEMA Example
To understand how ALTER SCHEMA works in SQL Server. First, create table named student in dbo schema.CREATE TABLE dbo.students ( roll_no INT PRIMARY KEY IDENTITY, first_name nvarchar(50) NOT NULL, last_name nvarchar(50) NOT NULL, phone_no nvarchar(20), address nvarchar(255) NOT NULL );Next, we will insert some data into it.
insert into dbo.students values ('Sagar','Sharma', 9523648645, 'Kolkata'), ('Shankar','Kumar', 9523652361, 'New Delhi'), ('Sajal','Roy', 7563145986, 'Hyderabad');

CREATE PROC students_by_id( @roll_no INT ) AS BEGIN SELECT * FROM dbo.students WHERE roll_no = @roll_no; END;After this, transfer this dbo.students table to university schema.
ALTER SCHEMA university TRANSFER object::dbo.students;The above statement will move the students table from dbo schema to university schema.

EXEC students_by_id 2; Msg 208, Level 16, State 1, Procedure students_by_id, Line 5 [Batch Start Line 77] Invalid object name 'dbo.students'.Finally, to reflect the correct schema name for the students table, you have to modify the procedure manually.
ALTER PROC students_by_id( @roll_no INT ) AS BEGIN SELECT * FROM university.students WHERE roll_no = @roll_no; END;Lastly if you execute the procedure again, it will give the correct output.
EXEC students_by_id 2;
