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>
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. <你的表名>
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!