📜  alter schema sql server - SQL (1)

📅  最后修改于: 2023-12-03 15:13:18.267000             🧑  作者: Mango

Altering Schema in SQL Server

In SQL Server, a schema is a collection of database objects, such as tables, views, triggers, and stored procedures. By default, every user has a schema with the same name as their user name. However, you can also create custom schemas to group related objects together.

There may be times when you need to alter the schema of your database objects. This could be because you want to move objects to a different schema, change the schema owner, or modify schema permissions. In this article, we will discuss different ways to alter a schema in SQL Server.

Altering Schema Owner

To change the owner of a schema, you can use the ALTER AUTHORIZATION statement. The following code snippet illustrates how to change the owner of the "dbo" schema to user "new_owner".

ALTER AUTHORIZATION ON SCHEMA::dbo TO new_owner;
Altering Schema Permissions

To modify the permissions of a schema, you can use the GRANT, DENY, or REVOKE statements. The following code snippets show some examples of how to use these statements.

Granting Permissions
GRANT SELECT ON SCHEMA::schema_name TO role_name;
Denying Permissions
DENY INSERT ON SCHEMA::schema_name TO user_name;
Revoking Permissions
REVOKE UPDATE ON SCHEMA::schema_name FROM user_name;
Moving Objects to a Different Schema

To move a table or other object to a different schema, you can use the ALTER SCHEMA statement. The following code snippet illustrates how to move the "my_table" table from the "dbo" schema to the "new_schema" schema.

ALTER SCHEMA new_schema TRANSFER dbo.my_table;
Conclusion

Altering a schema in SQL Server can be a useful way to manage your database objects. Whether you need to change the schema owner, modify schema permissions, or move objects to a different schema, SQL Server provides a variety of ways to accomplish these tasks.