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条回答
Viruses.
2楼-- · 2020-02-07 20:00
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'
查看更多
smile是对你的礼貌
3楼-- · 2020-02-07 20:00
EXEC sp_Pkeys @tableName
查看更多
▲ chillily
4楼-- · 2020-02-07 20:00

If you already know the name of the key you're interested in, following works:

-- 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
查看更多
别忘想泡老子
5楼-- · 2020-02-07 20:04

How about

sp_pkeys 'TableName'
查看更多
We Are One
6楼-- · 2020-02-07 20:04
exec [sys].[sp_primary_keys_rowset] @table_name= 'TableName'
查看更多
▲ chillily
7楼-- · 2020-02-07 20:06

This should get you started:

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'
查看更多
登录 后发表回答