使用TSQL确定表的主键

时间:2009-10-06 13:42:04

标签: sql sql-server tsql primary-key

我想使用TSQL确定表的主键(存储过程或系统表很好)。 SQL Server(2005或2008)中是否存在这样的机制?

10 个答案:

答案 0 :(得分:69)

这应该让你开始:

SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
        JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON tc.CONSTRAINT_NAME = ccu.Constraint_name
    WHERE tc.TABLE_NAME = 'TableName' and tc.CONSTRAINT_TYPE = 'Primary Key'

答案 1 :(得分:38)

怎么样

sp_pkeys 'TableName'

答案 2 :(得分:21)

这是一个基于SQL 2005的系统表(99%确定它在2008年工作)。这将列出所有用户定义的表的所有PK,所有列和一些可以删除的额外的绒毛。添加参数以一次挑选一个表。

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 :(得分:18)

SELECT ccu.COLUMN_NAME, ccu.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
    INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS ccu
        ON tc.CONSTRAINT_NAME = ccu.CONSTRAINT_NAME
WHERE tc.TABLE_CATALOG = 'Your_Catalog'    -- replace with your catalog
    AND tc.TABLE_SCHEMA = 'dbo'            -- replace with your schema
    AND tc.TABLE_NAME = 'Your_Table'       -- replace with your table name
    AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'

答案 4 :(得分:4)

EXEC sp_Pkeys @tableName

答案 5 :(得分:3)

exec [sys].[sp_primary_keys_rowset] @table_name= 'TableName'

答案 6 :(得分:2)

您最好使用INFORMATION_SCHEMA.KEY_COLUMN_USAGE,因为您可以访问非常重要的密钥订购信息(ORDINAL_POSITION)。

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

答案 7 :(得分:1)

最简单的方法就是这样!

select object_id from sys.objects 
where parent_object_id = OBJECT_ID(N'FACounty')
and [type] = N'PK'

答案 8 :(得分:1)

无法添加评论,表示点不足,但这是对有人说sp_Pkeys不可用的回应。不必是答案的另一条评论中提到的功能。

DECLARE @tbl TABLE
(
  Table_Qualifier varchar(30), 
  Table_Owner varchar(30), 
  Table_Name varchar(50), 
  Column_Name varchar(30), 
  Key_Seq int,
  PK_Name varchar(50)
)

insert into @tbl EXEC sp_Pkeys 'tablename'

select * from @tbl

答案 9 :(得分:0)

如果您已经知道您感兴趣的密钥的名称,请按以下方式工作:

-- Assuming you have schema "Example" and the primary key name is "PK_Item"
-- Notice that name of table is irrelevant here but is "Foobar" here
IF (OBJECT_ID('Example.PK_ITEM') IS NULL)
BEGIN
    ALTER TABLE [Example].Foobar ADD CONSTRAINT
    PK_Item PRIMARY KEY ...
END