Find PrimaryKey Columns on Table
here i want to know the Column Name on which the key constraints are created.
Initially i was concentrated on Primary Key constraints.
Here i am displaying Constraint Name ,Tablename ,ColumnName
SELECT i.name AS IndexName,
Object_name(ic.object_id) AS TableName,
Col_name(ic.object_id, ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
Object_name(ic.object_id) AS TableName,
Col_name(ic.object_id, ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
SELECT i.name AS IndexName,
Object_name(ic.object_id) AS TableName,
Col_name(ic.object_id, ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
Object_name(ic.object_id) AS TableName,
Col_name(ic.object_id, ic.column_id) AS ColumnName
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
If you want the table name only, use the CTE & to know the primarykey of a specific table you can filter it with table name
with cte as(
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i INNER JOIN sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
)select * from cte
--where TableName='Document'
SELECT i.name AS IndexName,
OBJECT_NAME(ic.OBJECT_ID) AS TableName,
COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM sys.indexes AS i INNER JOIN sys.index_columns AS ic ON i.OBJECT_ID = ic.OBJECT_ID
AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
)select * from cte
--where TableName='Document'