To change the schema of a table by using SQL Server Management Studio, in Object Explorer, right-click on the table and then click Design. Press F4 to open the Properties window. In the Schema box, select a new schema. ALTER SCHEMA uses a schema level lock.
To change the schema and table name both, first we have to rename the table using SP_RENAME and then transfer the schema using ALTER SCHEMA command.
In SQL, we cannot RENAME a SCHEMA. To achieve this, we need to create a new SCHEMA, transfer all the contents(objects) from the old schema to new schema and then finally delete the old schema using the DROP command.
Create Schema :
IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'exe'))
BEGIN
EXEC ('CREATE SCHEMA [exe] AUTHORIZATION [dbo]')
END
ALTER Schema :
ALTER SCHEMA exe
TRANSFER dbo.Employees
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA
query in SQL, or I get an error message.
Try below
declare @sql varchar(8000), @table varchar(1000), @oldschema varchar(1000), @newschema varchar(1000)
set @oldschema = 'dbo'
set @newschema = 'exe'
while exists(select * from sys.tables where schema_name(schema_id) = @oldschema)
begin
select @table = name from sys.tables
where object_id in(select min(object_id) from sys.tables where schema_name(schema_id) = @oldschema)
set @sql = 'alter schema ' + @newschema + ' transfer ' + @oldschema + '.' + @table
exec(@sql)
end
CREATE SCHEMA exe AUTHORIZATION [dbo]
GO
ALTER SCHEMA exe
TRANSFER dbo.Employees
GO
Through SSMS, I created a new schema by:
I found this post to change the schema, but was also getting the same permissions error when trying to change to the new schema. I have several databases listed in my SSMS, so I just tried specifying the database and it worked:
USE (yourservername)
ALTER SCHEMA exe TRANSFER dbo.Employees
Your Code is:
FROM
dbo.Employees
TO
exe.Employees
I tried with this query.
ALTER SCHEMA exe TRANSFER dbo.Employees
Just write create schema exe
and execute it
Check out MSDN...
CREATE SCHEMA
: http://msdn.microsoft.com/en-us/library/ms189462.aspx
Then
ALTER SCHEMA
: http://msdn.microsoft.com/en-us/library/ms173423.aspx
Or you can check it on on SO...
How do I move a table into a schema in T-SQL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With