Get primary key from table name

Get primary key from table name
DECLARE @tableName varchar(50)
select @tableName = ‘@tablename’ — exclude schema
SELECT [name] as primarykeyname
FROM syscolumns
WHERE [id] IN ( SELECT [id]
FROM sysobjects
WHERE [name] = (@tableName))
AND colid IN (SELECT SIK.colid
FROM sysindexkeys SIK
JOIN sysobjects SO ON SIK.[id] = SO.[id]
WHERE SIK.indid = 1
AND SO.[name] = @tableName)

Advertisement

Post a Comment

Required fields are marked *
*
*

Follow

Get every new post delivered to your Inbox.