While not disputing that the most comprehensive method is to use SMO as Remus suggested in his answer, this question does request to get the info via T-SQL and that info does exist for some objects. Just keep in mind that this info:
- covers a small set of object types
- does not include any
GRANT
/ DENY
statements. But you can get that info from sys.database_permissions
and sys.database_principals
.
- does not include any
IF EXISTS DROP
logic
- does not include the session settings of
ANSI_NULLS
and QUOTED_IDENTIFIER
. Those you get from sys.sql_modules
via the [uses_ansi_nulls]
and [uses_quoted_identifier]
fields.
- might not include the Schema Name. If the Schema Name was not explicitly stated in the CREATE (or ALTER) statement, then the Schema Name will not be a part of the definition. The Schema will have been whatever the default Schema was for the User that created the object, at the time of creation. If the Schema Name is not included in the definition and cannot be assumed to be something like
dbo
, then it will have to be discovered via OBJECT_SCHEMA_NAME([object_id])
Object Catalog Views
The sys.sql_modules Catalog View has the full CREATE...
statement for the following objects (anything encrypted will return NULL
for the [definition]
):
- SQL Stored Procedure
- Replication-filter-procedure
- View
- SQL DML trigger
- SQL Database-level DDL trigger
- SQL scalar function
- SQL inline table-valued function
- SQL table-valued-function
- Rule (old-style, stand-alone)
- Default (stand-alone, NOT constraint)
SELECT OBJECT_SCHEMA_NAME([object_id]) AS [SchemaName],
OBJECT_NAME([object_id]) AS [ObjectName],
*
FROM sys.sql_modules;
The sys.check_constraints and sys.default_constraints Catalog Views will return the logic portion of their respective constraints as the [definition]
:
SELECT *
FROM sys.check_constraints;
SELECT *
FROM sys.default_constraints;
Metadata Function
The OBJECT_DEFINITION function will return the same data that is in the [definition]
field of the three previously mentioned Catalog Views, based on the specified [object_id]
:
SELECT so.name,
so.[type],
so.type_desc,
OBJECT_DEFINITION(so.[object_id]) AS [Definiton]
FROM sys.objects so
WHERE OBJECT_DEFINITION(so.[object_id]) IS NOT NULL;
Other Objects
Here are some resources for finding the meta-data related to all object types:
with
options, allcascades
on foreign keys, etc.