获取在数据库中的唯一约束和索引列表(Get the list of unique constrain

2019-07-30 23:05发布

我得的所有唯一键约束列表和特定数据库的索引。 我做这样的事情:

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

只是想确认这是否是正确的方法,或者是有做同样的事情的一个更好的办法?

Answer 1:

由于唯一约束的封面作为指标下实现的,你可以得到所有的这些信息直接从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');

要重复所有数据库(可能不特定表过滤器):

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;


Answer 2:

其他答案并没有为我返回完整列表。 此查询工作对我来说要退回没有主键或系统表的所有唯一索引:

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'


Answer 3:

一个独特的约束在由类型“UQ” sys.objects中表示

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

要获得索引

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


Answer 4:

你可以得到独特的主要制约因素,并从SYS.INDEXES索引。 具体地,唯一约束:

select * from sys.indexes where is_unique_constraint = 1


文章来源: Get the list of unique constraints and indexes in a database