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 :(得分:3)
试试这个:
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
答案 1 :(得分: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
答案 2 :(得分: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