SQL Server obtains the primary key for the specified table

Source: Internet
Author: User

Sometimes to get the table primary key field, although the system from the stored procedure can be obtained, but for familiar with the system table, it is easy to write yourself.

2     Declare @table_name varchar 3     Set @table_name = ' TABLE_PQS ' 4     --1, can be based on system stored procedure 5     Execute   sp_ Pkeys @table_name 6  7     --2, obtained 8     Declare @objectid int 9     Set @objectid =object_id (@table_name) 10 according to system table     Select   One     col_name (@objectid, colid)  ' primary key field ' from  sysobjects as         o13     Inner join sysindexes as    i on I.name=o.name     Inner Join Sysindexkeys as  K on k.indid=i.indid15     wher E     o.xtype = ' PK ' and [email protected] and [email protected]

sysobjects (object table),sysindexes (Index Table),Sysindexkeys ( index key table) are applied here. This query obtains the index of the primary key in the object table directly.

SQL Server obtains the primary key for the specified 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.