Jump to content

Recommended Posts

I've been looking how to find the Primary Key of a table similar to the mysql equivalent of something like

 

show keys from table1 where Key_name = 'primary'

 

So far i have got this stage:

 

SELECT
kcu.COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on kcu.TABLE_NAME = tc.TABLE_NAME
WHERE
tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND kcu.TABLE_NAME = 'table1'

 

However, if the table contains a Foreign Key field that is a Primary Key on a nother table, it returns it in the query.

 

Does any one know of a way to return ONLY the Primary Key of a table and nothing else?

 

Thanks

Solved, i was joining my tables on the table name and not the constraint name (which is where i should have been joining).

 

Incase this is of use to anyone:

 

SELECT  
    kcu.COLUMN_NAME 
FROM  
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc 
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME  
WHERE 
    tc.CONSTRAINT_TYPE = 'PRIMARY KEY'  
    AND tc.TABLE_NAME = 'table1'

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.