Get the list of unique constraints and indexes in a database

*爱你&永不变心* 提交于 2019-12-14 00:23:36

问题


I have to get the list of all the unique key constraints and the indexes of a particular database. I am doing something like this:

SELECT * FROM sys.sysobjects WHERE type!='u' AND name LIKE <tablename> 

Just wanted to confirm if this was the correct way, or is there a better way of doing the same thing?


回答1:


Since unique constraints are implemented under the covers as indexes, you can get all of this information directly from sys.indexes:

SELECT
  [schema] = OBJECT_SCHEMA_NAME([object_id]),
  [table]  = OBJECT_NAME([object_id]),
  [index]  = name, 
  is_unique_constraint,
  is_unique,
  is_primary_key
FROM sys.indexes
-- WHERE [object_id] = OBJECT_ID('dbo.tablename');

To repeat for all databases (and presumably without the filter for a specific table):

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += 'SELECT db = ' + name + ',
    [schema] = OBJECT_SCHEMA_NAME([object_id]),
    [table]  = OBJECT_NAME([object_id]),
    [index]  = name, 
    is_unique_constraint,
    is_unique,
    is_primary_key
  FROM ' + QUOTENAME(name) + '.sys.indexes;'
FROM sys.databases
WHERE database_id BETWEEN 4 AND 32766;

EXEC sp_executesql @sql;



回答2:


A unique constraint is represented in sys.objects by the type 'UQ'

 select name from sys.objects where type='UQ'

To get the indexes

 select i.name, o.name from sys.indexes i
inner join sys.objects o on i.object_id= o.object_id



回答3:


You can get the unique key constraints, and indexes from sys.indexes. Specifically, unique constraints:

select * from sys.indexes where is_unique_constraint = 1



回答4:


The other answers did not return complete lists for me. This query worked for me to return all unique indexes that are not primary keys or system tables:

select i.name as index_name, o.name as object_name
from sys.indexes i
    join sys.objects o on i.object_id= o.object_id
where (i.is_unique_constraint = 1 OR i.is_unique = 1) 
    and i.is_primary_key = 0 and o.type_desc <> 'SYSTEM_TABLE'


来源:https://stackoverflow.com/questions/11941118/get-the-list-of-unique-constraints-and-indexes-in-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!