Friday 11 July 2014

List All Primary Key Columns Within a Database

SELECT
schema_name(ta.schema_id)  SchemaName
,ta.name  TableName
,col.name  ColumnName
,indcol.key_ordinal IndexPositoin
,ind.name IndexName
,ind.type_desc IndexType
,ind.fill_factor Fill_Factor
from sys.tables ta inner join sys.indexes ind
on ind.object_id = ta.object_id
inner join sys.index_columns indcol
on indcol.object_id = ta.object_id
and indcol.index_id = ind.index_id
inner join sys.columns col
on col.object_id = ta.object_id
and col.column_id = indcol.column_id
where ind.is_primary_key = 1
order by 1,2,4

Wednesday 9 July 2014

List of all FK in a database

SELECT
OBJECT_NAME(referenced_object_id) 'Referenced table'
,OBJECT_NAME(parent_object_id) 'Parent table'
,cref.NAME 'Referenced column name'
,c.NAME 'Parent column name'
FROM sys.foreign_key_columns fkc INNER JOIN sys.columns c
ON fkc.parent_column_id = c.column_id AND fkc.parent_object_id = c.object_id
INNER JOIN sys.columns cref
ON fkc.referenced_column_id = cref.column_id AND fkc.referenced_object_id = cref.object_id
--where   OBJECT_NAME(parent_object_id) = 'tablename'
order by 1, 2