Home > Database > Mysql Tutorial > How to Retrieve a SQL Server Table's Primary Key Using SQL?

How to Retrieve a SQL Server Table's Primary Key Using SQL?

Mary-Kate Olsen
Release: 2025-01-03 20:13:41
Original
512 people have browsed it

How to Retrieve a SQL Server Table's Primary Key Using SQL?

SQL Server: Retrieving Table Primary Key using SQL Query

In SQL Server databases, one can retrieve the primary key of a table using a specific SQL query. This query differs from the one used in MySQL databases.

SQL Server Query:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'TableName' AND TABLE_SCHEMA = 'Schema'
Copy after login

Parameters:

  • TableName: The name of the table whose primary key you want to retrieve.
  • Schema: The schema to which the table belongs.

Example:

To retrieve the primary key of the "Products" table in the "dbo" schema:

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID('dbo.Products'), 'IsPrimaryKey') = 1
AND TABLE_NAME = 'Products' AND TABLE_SCHEMA = 'dbo'
Copy after login

Alternative Query for Both MySQL and SQL Server:

While the above query is specific to SQL Server, there is an alternative query that can work for both MySQL and SQL Server:

SHOW COLUMNS FROM `TableName` WHERE `Key` = 'PRI'
Copy after login

This query will retrieve the column with the 'PRI' key, which represents the primary key in both MySQL and SQL Server.

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

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