开发者

Getting table primary key columns by query

开发者 https://www.devze.com 2023-02-17 14:38 出处:网络
SELECT [name] FROM syscolumns WHERE [id] IN (SELECT [id] FROM sysobjects WHERE [name] = \'ACTIVITY\')
SELECT [name]
FROM syscolumns 
 WHERE [id] IN (SELECT [id] 
                  FROM sysobjects 
                 WHERE [name] = 'ACTIVITY')
   AND colid IN (SELECT SIK.colid 
                   FROM sysindexkeys SIK 
                   JOIN sysobjects SO ON SIK.[id] = SO.[id]  
                    AND SO.[name] = '开发者_运维技巧ACTIVITY')

It is returning all the columns by id. I need only the primary key. When I add the following line it is empty:

                  WHERE SIK.indid = 1

Why is that? Is there other ways to do the same thing and working? Since I am in the rush


Try this:

Declare @TableName varchar(128)

Set @TableName = 'YourTableName'

SELECT c.COLUMN_NAME as [PrimaryKeyColumns]

FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,              
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE c       
WHERE   pk.TABLE_NAME = @TableName      
AND     CONSTRAINT_TYPE = 'PRIMARY KEY'       
AND     c.TABLE_NAME = pk.TABLE_NAME       
AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME


This SQL will find all tables with primary keys:

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

I got it from here. There are some other examples here.


This is the SQL that I use to return the primary key(s) for a table in SQL Server.

DECLARE @TableSchema varchar(255)
SET @TableSchema = 'dbo'
SET @TableName = 'table_name_here'

SELECT 
    ColumnName = col.column_name
FROM    
    information_schema.table_constraints tc               
    INNER JOIN information_schema.key_column_usage col
        ON col.Constraint_Name = tc.Constraint_Name
        AND col.Constraint_schema = tc.Constraint_schema    
WHERE 
    tc.Constraint_Type = 'Primary Key'
    AND col.Table_name = @TableName
    AND col.Table_Schema = @TableSchema
0

精彩评论

暂无评论...
验证码 换一张
取 消