During a job interview, candidates may encounter open-ended questions that allow them to showcase their knowledge and skills. One such question that a database administrator might face is, “What is your favorite T-SQL script?”
One possible answer to this question involves retrieving user-defined object details using the sys.objects
catalog view in SQL Server. The sys.objects
view contains a row for each user-defined, schema-scoped object created within a database.
Let’s take a look at an example script that demonstrates how to retrieve user-defined object details:
USE AdventureWorks;
GO
SELECT
name AS ObjectName,
OBJECT_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS ParentObjectName,
name,
*
FROM sys.objects
WHERE TYPE = 'F';
GO
In this example, the script retrieves information about foreign keys in the AdventureWorks database. It returns the name of the foreign key, the name of the table to which the foreign key belongs, and the schema owner name of the table.
You can modify the WHERE
clause to retrieve information about other types of user-defined objects. For example, you can use TYPE = 'U'
to retrieve information about user-defined tables, or TYPE = 'V'
to retrieve information about views.
Here are some commonly used object types and their corresponding codes:
- AF: Aggregate function (CLR)
- C: CHECK constraint
- D: DEFAULT (constraint or stand-alone)
- F: FOREIGN KEY constraint
- PK: PRIMARY KEY constraint
- P: SQL stored procedure
- PC: Assembly (CLR) stored procedure
- FN: SQL scalar function
- FS: Assembly (CLR) scalar function
- FT: Assembly (CLR) table-valued function
- R: Rule (old-style, stand-alone)
- RF: Replication-filter-procedure
- S: System base table
- SN: Synonym
- SQ: Service queue
- TA: Assembly (CLR) DML trigger
- TR: SQL DML trigger
- IF: SQL inline table-valued function
- TF: SQL table-valued function
- U: Table (user-defined)
- UQ: UNIQUE constraint
- V: View
- X: Extended stored procedure
- IT: Internal table
By utilizing the sys.objects
catalog view and understanding the different object types, you can retrieve specific details about user-defined objects in your SQL Server database.