Determine a table's primary key using TSQL

2020-02-07 19:42发布

I'd like to determine the primary key of a table using TSQL (stored procedure or system table is fine). Is there such a mechanism in SQL Server (2005 or 2008)?

9条回答
beautiful°
2楼-- · 2020-02-07 20:07

Here's one based on system tables from SQL 2005 (99% sure it'd work in 2008). This will list all PKs for all user-defined tables, with all columns and some extra fluff that could be removed. Add parameters to pick out a table at a time.

SELECT
   schema_name(ta.schema_id)  SchemaName
  ,ta.name  TableName
  ,ind.name
  ,indcol.key_ordinal Ord
  ,col.name  ColumnName
  ,ind.type_desc
  ,ind.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
   ta.name
  ,indcol.key_ordinal
查看更多
聊天终结者
3楼-- · 2020-02-07 20:09

The simplest way is this!

select object_id from sys.objects 
where parent_object_id = OBJECT_ID(N'FACounty')
and [type] = N'PK'
查看更多
Luminary・发光体
4楼-- · 2020-02-07 20:13

You're better off using INFORMATION_SCHEMA.KEY_COLUMN_USAGE, as you can access the key ordering information (ORDINAL_POSITION) which is very important to know.

SELECT 
    kcu.*
FROM 
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
    INNER JOIN 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
        ON  tc.TABLE_NAME = kcu.TABLE_NAME AND 
            tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
ORDER BY 
    tc.TABLE_NAME,
    tc.CONSTRAINT_NAME,
    kcu.ORDINAL_POSITION
查看更多
登录 后发表回答