Home >Database >Mysql Tutorial >How to Find a SQL Server Table's Primary Key Using T-SQL?
Finding the Primary Key of a SQL Server Table Using T-SQL
This T-SQL query efficiently identifies the primary key column(s) for any given SQL Server table.
<code class="language-sql">SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_NAME = '<your_table_name>' AND CONSTRAINT_NAME = (SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = '<your_table_name>' AND CONSTRAINT_TYPE = 'PRIMARY KEY');</code>
The query uses INFORMATION_SCHEMA.KEY_COLUMN_USAGE
to pinpoint columns associated with constraints and INFORMATION_SCHEMA.TABLE_CONSTRAINTS
to filter for primary key constraints, ensuring only the primary key column names are returned for the specified table. Replace <your_table_name>
with the actual name of your table.
The above is the detailed content of How to Find a SQL Server Table's Primary Key Using T-SQL?. For more information, please follow other related articles on the PHP Chinese website!