primary/foreign keys or indexes in a give table
/**
* This script will returns a resultset of rows containing primary/foreign keys or
indexes in a given table.
**/
declare @tbl nvarchar(500)
set @tbl = 'tableName'
select
object_name(i.object_id) as [Table Name],
c.[name] as [Column Name],
i.[name] as [Constraint Name],
case when i.type = 1 then 'CLUSTERED'
when i.type = 2 then 'NON-CLUSTERED' end as [Index Type],
case when i.is_unique = 1 and i.is_primary_key = 1 then 'PRIMARY KEY CONSTRAINT'
when i.is_unique = 1 and i.is_primary_key = 0 and i.is_unique_constraint = 1 then 'UNIQUE CONSTRAINT'
when i.is_unique = 1 and i.is_primary_key = 0 and i.is_unique_constraint = 0 then 'UNIQUE INDEX'
when i.is_unique = 0 and i.is_primary_key = 0 and i.is_unique_constraint = 0 then 'NON-UNIQUE INDEX'
end as [Constraint Type]
from sys.indexes i
inner join sys.index_columns ic
on i.index_id = ic.index_id
and i.object_id = ic.object_id
and (i.is_unique = 1 or i.is_primary_key = 1 or i.is_unique_constraint = 1 or i.type in (1,2))
inner join sys.columns c
on c.column_id = ic.column_id and c.object_id = i.object_id
where i.object_id = object_id(@tbl)
* This script will returns a resultset of rows containing primary/foreign keys or
indexes in a given table.
**/
declare @tbl nvarchar(500)
set @tbl = 'tableName'
select
object_name(i.object_id) as [Table Name],
c.[name] as [Column Name],
i.[name] as [Constraint Name],
case when i.type = 1 then 'CLUSTERED'
when i.type = 2 then 'NON-CLUSTERED' end as [Index Type],
case when i.is_unique = 1 and i.is_primary_key = 1 then 'PRIMARY KEY CONSTRAINT'
when i.is_unique = 1 and i.is_primary_key = 0 and i.is_unique_constraint = 1 then 'UNIQUE CONSTRAINT'
when i.is_unique = 1 and i.is_primary_key = 0 and i.is_unique_constraint = 0 then 'UNIQUE INDEX'
when i.is_unique = 0 and i.is_primary_key = 0 and i.is_unique_constraint = 0 then 'NON-UNIQUE INDEX'
end as [Constraint Type]
from sys.indexes i
inner join sys.index_columns ic
on i.index_id = ic.index_id
and i.object_id = ic.object_id
and (i.is_unique = 1 or i.is_primary_key = 1 or i.is_unique_constraint = 1 or i.type in (1,2))
inner join sys.columns c
on c.column_id = ic.column_id and c.object_id = i.object_id
where i.object_id = object_id(@tbl)
Comments
Post a Comment