我用下面的查詢來檢索SQL Server 2012中的約束信息,並且完美地工作。我希望它對你有用。
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
感謝您的幫助馬克,但我希望使用sysObjects自己的查詢。是否有一種方法來調整我的查詢,以獲得所需的結果? – unos
您的查詢僅列出第一個表中的第一個約束。 –
@SteveStaple:不,它不會.....我一直在使用它 - 它列出了所有**表的所有**約束!在「AdventureWorks」上試用 - 我獲得了152行,並且幾個表有多個約束,例如'員工'表具有不少於六個約束,所有這些都顯示得很好.... –