SQL Server 2008- Get table constraints
You should use the current sys
catalog views (if you're on SQL Server 2005 or newer - the sysobjects
views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.
There are quite a few views you might be interested in:
-
sys.default_constraints
for default constraints on columns -
sys.check_constraints
for check constraints on columns -
sys.key_constraints
for key constraints (e.g. primary keys) -
sys.foreign_keys
for foreign key relations
and a lot more - check it out!
You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:
SELECT
TableName = t.Name,
ColumnName = c.Name,
dc.Name,
dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name
I used the following query to retrieve the information of constraints in the SQL Server 2012, and works perfectly. I hope it would be useful for you.
SELECT
tab.name AS [Table]
,tab.id AS [Table Id]
,constr.name AS [Constraint Name]
,constr.xtype AS [Constraint Type]
,CASE constr.xtype WHEN 'PK' THEN 'Primary Key' WHEN 'UQ' THEN 'Unique' ELSE '' END AS [Constraint Name]
,i.index_id AS [Index ID]
,ic.column_id AS [Column ID]
,clmns.name AS [Column Name]
,clmns.max_length AS [Column Max Length]
,clmns.precision AS [Column Precision]
,CASE WHEN clmns.is_nullable = 0 THEN 'NO' ELSE 'YES' END AS [Column Nullable]
,CASE WHEN clmns.is_identity = 0 THEN 'NO' ELSE 'YES' END AS [Column IS IDENTITY]
FROM SysObjects AS tab
INNER JOIN SysObjects AS constr ON(constr.parent_obj = tab.id AND constr.type = 'K')
INNER JOIN sys.indexes AS i ON( (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tab.id) AND i.name = constr.name )
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0))
AND (ic.index_id=CAST(i.index_id AS int)
AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE tab.xtype = 'U'
ORDER BY tab.name