Get a List of all Primary Keys in a Database

白昼怎懂夜的黑 提交于 2019-12-02 20:54:25

look on link

EXEC sp_pkeys '<tablename>'
EXEC sp_helpconstraint '<tablename>'

sp_pkeys will return a row for each column that participates in the primary key for . The columns you are likely most interested in are COLUMN_NAME and PK_NAME.

sp_helpconstraint will list all constraints for , including foreign keys that reference the table. In the first recordset, there will only be a column called Object Name (kind of useless, since that's what you passed in). In the second resultset, there will be the following columns: constraint_type, constraint_name, and constraint_keys.

Kapil
USE databasename; 

GO

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

This query will extract the all primary key constraints from the database... u just need to execute this query and type the database name in first line

The following syntax give you all constraints in database in use.

select * from sys.key_constraints;

If you want the data type information as well:

SELECT 
    so.name 'Table Name',
    c.name 'Column Name',
    t.Name 'Data type',
    c.max_length 'Max Length',
    c.precision ,
    c.scale ,
    c.is_nullable,
    ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM    
    sys.columns c
INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN 
    sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN 
    sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
INNER JOIN 
    sysobjects so ON c.object_id = so.id
WHERE
    i.is_primary_key = 1 and 
    so.xtype = 'U'
Order By 'Table Name', 'Column Name'

If you are doing this from java you can also use the getPrimaryKeys method in the databasemetadata object. Perhaps other languages have similar ways to do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!