Question

I know the query to get the table names of database is :

SELECT * 
FROM information_schema.tables 
WHERE table_type = 'BASE TABLE'

How to get the table if its primary key is made up from multiple columns? Or get composite primary key for a specific table?

Was it helpful?

Solution

If I understood well, you can have some options with TSQL.

Procedure:

exec sp_pkeys 'table', 'schema'

View:

This query will return related data with unique constraints e foreign_keys as well

select * from information_schema.key_column_usage
where table_schema = 'schema' and table_name = 'table'

If you want to get just the columns related with primary keys you can try something similar bellow. I think it can change with the database version, I am not sure now.

select * 
  from information_schema.key_column_usage as k
 where table_schema = 'schema' and table_name = 'table'
   and constraint_name = (
    select name 
      from sysobjects as u
     where k.table_name = object_name(u.parent_obj)
       and u.xtype = 'PK')
  order by table_schema, table_name, ordinal_position

If it's not the answer give us more details.

OTHER TIPS

Try this:

sp_helpindex 'YourTable'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top