Sometimes you need to obtain the table primary key field. Although the system can obtain it from a stored procedure, you can easily write it yourself if you are familiar with the system table. 2 declare @ table_name varchar (100)
3 set @ table_name = 'table _ pqs'
4 -- 1. You can use the Stored Procedure
5 execute sp_pkeys @ table_name
6
7 -- 2. obtain from the system table
8 declare @ objectid int
9 set @ objectid = object_id (@ table_name)
10 select
11 col_name (@ objectid, colid) 'Primary key field'
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
Here, sysobjects (Object table), sysindexes (index table), and sysindexkeys (index key table) are applied ).
This query directly obtains the index of the primary key in the object table.