Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a column is in the primary key of its table? (SQL Server)

Tags:

I am currently using...

select Table_Name, Column_name, data_type, is_Nullable from information_Schema.Columns 

...to determine information about columns in a given database for the purposes of generating a DataAccess Layer.

From where can I retrieve information about if these columns are participants in the primary key of their table?

like image 670
Rory Becker Avatar asked Oct 21 '08 15:10

Rory Becker


People also ask

How do you tell if a column is a primary key?

To identify a primary key for a table or file, you locate a column that's values uniquely identify the rows in the selected table. Additionally, you can verify that a primary key that is defined in the data source is the true primary key.

How we can identify primary key?

Columns that have a high percentage of uniqueness, as well as at least one foreign key candidate, make the best primary key candidates. Identify the columns that have the highest uniqueness percentage and assign one of the columns as the primary key. You might only have one primary key per table.

How can we get list of primary key and foreign key of the table in SQL Server?

If we want to know the table's primary keys and foreign keys. We can simply use an “information_schema. key_column_usage” view, this view will return all of the table's foreign keys and primary keys.


1 Answers

Here is one way (replace 'keycol' with the column name you are searching for):

SELECT  K.TABLE_NAME ,     K.COLUMN_NAME ,     K.CONSTRAINT_NAME FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C         JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME                                                          AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG                                                          AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA                                                          AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME WHERE   C.CONSTRAINT_TYPE = 'PRIMARY KEY'         AND K.COLUMN_NAME = 'keycol'; 
like image 188
Galwegian Avatar answered Sep 20 '22 08:09

Galwegian