SQL Server obtains the primary key of the specified table.

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.