Home > Database > Mysql Tutorial > How to Retrieve Primary Key Column Names from a SQL Server Table?

How to Retrieve Primary Key Column Names from a SQL Server Table?

Mary-Kate Olsen
Release: 2025-01-13 11:01:46
Original
532 people have browsed it

How to Retrieve Primary Key Column Names from a SQL Server Table?

Get primary key information from SQL Server table

When working with SQL Server tables, access to primary key information is critical for data integrity and efficient query execution. This article explores how to list the primary keys of a SQL Server table using Transact-SQL (T-SQL).

Query to list primary keys

To get the primary key information for a specific table, execute the following query:

<code class="language-sql">SELECT Col.Column_Name
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab,
     INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col
WHERE Col.Constraint_Name = Tab.Constraint_Name
  AND Col.Table_Name = Tab.Table_Name
  AND Tab.Constraint_Type = 'PRIMARY KEY'
  AND Col.Table_Name = '<你的表名>'</code>
Copy after login

Query instructions:

  • INFORMATION_SCHEMA.TABLE_CONSTRAINTS Provides information about constraints on the table, including primary keys.
  • INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Links the constraint to the column to which it applies.
  • Tab.Constraint_Type = 'PRIMARY KEY' Filters the results to contain only primary key constraints.
  • Replace <你的表名> with the name of the table whose primary keys you want to list.

After executing this query, you will retrieve a list of column names in the specified table that are specified as part of the primary key.

The above is the detailed content of How to Retrieve Primary Key Column Names from a SQL Server Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template