2011-03-17 164 views
2
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') 

它通過id返回所有列。我只需要主鍵。當我添加以下行時,它是空的:通過查詢獲取表主鍵列

    WHERE SIK.indid = 1 

這是爲什麼?還有其他方法可以做同樣的事情嗎?因爲我在搶

+0

'indid = 1'只會提供有關表上聚簇索引的信息(如果有)。不能保證主鍵和聚簇索引是相同的東西。 – 2011-03-17 10:07:06

回答

2

試試這個:

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 
0

這個SQL會發現所有的表與主鍵:

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 

我從here得到它。還有一些其他示例here

0

這是我用來返回SQL Server中的表的主鍵的SQL。

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