T-SQL Tutorial

How to get SQL Server schema name


In SQL Server, a schema is a logical container that groups related database objects, such as tables, views, stored procedures, and functions. Each object belongs to a specific schema, which helps organize and manage database objects effectively. Knowing the schema name is crucial for accessing and interacting with specific database objects.

To retrieve the schema name in SQL Server, you can use various methods depending on your specific requirements and the version of SQL Server you are using. Here are some common ways to get the schema name:


Using the INFORMATION_SCHEMA

The INFORMATION_SCHEMA is a system catalog in SQL Server that contains information about database objects, including schemas. You can use the INFORMATION_SCHEMA.SCHEMATA view to retrieve schema names.

SELECT schema_name
FROM INFORMATION_SCHEMA.SCHEMATA;

This query will return a list of all schema names in the current database.


Using the sys.schemas system view

In SQL Server, you can also query the sys.schemas system view to get schema names. This view provides more detailed information about schemas.

SELECT name
FROM sys.schemas;

This query will return a list of schema names along with additional information about each schema.


Retrieving schema for a specific object

If you want to find the schema associated with a specific database object (e.g., a table, view, or stored procedure), you can query the sys.objects system view.

SELECT s.name AS schema_name, o.name AS object_name
FROM sys.objects o
JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.type = 'U';

This query will return the schema name for the specified object.






Using system functions

SQL Server provides system functions like SCHEMA_NAME() to retrieve the schema name associated with an object or session.
To get the default schema for the current user or session:

SELECT SCHEMA_NAME() AS default_schema;

These methods should help you retrieve schema names in SQL Server based on your requirements and context.

In addition to these methods, you can also use SQL Server Management Studio (SSMS) to view schema names. In SSMS, expand the "Databases" node, select the desired database, and then expand the "Security" folder. The schemas will be listed under the "Schemas" node.

By understanding the different methods for retrieving schema names, you can effectively manage and interact with database objects in SQL Server.