- 这种方法会把其他键 都查出来
--查詢主鍵信息
SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME='表名'
https://www.cnblogs.com/piaoqingsong/archive/2007/05/18/751533.html
- 使用这种
Declare @table_name varchar(100)
Set @table_name='table_Pqs'
--1、可以根据系统存储过程
Execute sp_pkeys @table_name
- 自定义
有时候要获得表主键字段,虽然系统自带有存储过程可以获得,但是对于熟悉系统表的话,自己写个也很容易。
Declare @table_name varchar(100)
Set @table_name='table_Pqs'
--2、根据系统表获得
Declare @objectid int
Set @objectid=object_id(@table_name)
Select
col_name(@objectid,colid) '主键字段'
From sysobjects as o
Inner Join sysindexes as i On i.name=o.name
Inner Join sysindexkeys as k On k.indid=i.indid
Where
o.xtype = 'PK' and parent_obj=@objectid and k.id=@objectid
这里应用了sysobjects(对象表),sysindexes(索引表),sysindexkeys(索引键表)。
这个查询直接获取对象表里主键的索引来获得的。
SQL Server查询主键约束
SQL70版本,新版本向下兼容:
select kcu.TABLE_SCHEMA, kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.COLUMN_NAME, kcu.ORDINAL_POSITION
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
join INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu
on kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
and kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
and kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA
and kcu.TABLE_NAME = tc.TABLE_NAME
where tc.CONSTRAINT_TYPE = 'PRIMARY KEY';
SQL2005以后的查询SQL:
select
s.name as TABLE_SCHEMA
, t.name as TABLE_NAME
, k.name as CONSTRAINT_NAME
, c.name as COLUMN_NAME
, typ.name AS DATA_TYPE
, ic.key_ordinal AS ORDINAL_POSITION
from sys.key_constraints as k -- 主键信息
join sys.tables as t on t.object_id = k.parent_object_id -- 获取表名
join sys.schemas as s on s.schema_id = t.schema_id -- 获取数据库名
join sys.index_columns as ic on ic.object_id = t.object_id and ic.index_id = k.unique_index_id -- 获取key顺序
join sys.columns as c on c.object_id = t.object_id and c.column_id = ic.column_id -- 获取列名称
LEFT JOIN sys.types typ ON typ.system_type_id = c.system_type_id -- 列类型
where k.type = 'PK' AND t.name = 'Qty_Plan';
查出来两个主键???
查询类型
SELECT col.name, typ.name FROM sys.columns col
LEFT JOIN sys.types typ ON typ.system_type_id = col.system_type_id
WHERE object_id = OBJECT_ID('TestTable')