有时候要获得表主键字段,虽然系统自带有存储过程可以获得,但是对于熟悉系统表的话,自己写个也很容易。
2
Declare
@table_name
varchar
(
100
)
3 Set @table_name = ' table_Pqs '
4 -- 1、可以根据系统存储过程
5 Execute sp_pkeys @table_name
6
7 -- 2、根据系统表获得
8 Declare @objectid int
9 Set @objectid = object_id ( @table_name )
10 Select
11 col_name ( @objectid ,colid) ' 主键字段 '
12 From sysobjects as o
13 Inner Join sysindexes as i On i.name = o.name
14 Inner Join sysindexkeys as k On k.indid = i.indid
15 Where
16 o.xtype = ' PK ' and parent_obj = @objectid and k.id = @objectid
3 Set @table_name = ' table_Pqs '
4 -- 1、可以根据系统存储过程
5 Execute sp_pkeys @table_name
6
7 -- 2、根据系统表获得
8 Declare @objectid int
9 Set @objectid = object_id ( @table_name )
10 Select
11 col_name ( @objectid ,colid) ' 主键字段 '
12 From sysobjects as o
13 Inner Join sysindexes as i On i.name = o.name
14 Inner Join sysindexkeys as k On k.indid = i.indid
15 Where
16 o.xtype = ' PK ' and parent_obj = @objectid and k.id = @objectid
这里应用了 sysobjects(对象表), sysindexes(索引表), sysindexkeys( 索引键表)。
这个查询直接获取对象表里主键的索引来获得的。