How to determine the primary key for a table in SQL Server?

后端 未结 8 2027
小蘑菇
小蘑菇 2020-12-16 07:13

What I\'d like to be able to do in SQL Server 2005 somehow is with a table name as input determine all the fields that make up the primary key. sp_columns doesn

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 07:26

    I ended up using this...

    select  cu.constraint_catalog, 
            cu.constraint_schema, 
            cu.table_name, 
            cu.constraint_name, 
            constraint_type, 
            column_name, 
            ordinal_position
    
    from    information_schema.key_column_usage cu 
    
            join information_schema.table_constraints as tc
                on tc.constraint_catalog = cu.constraint_catalog and 
                    tc.constraint_schema = cu.constraint_schema and 
                    tc.constraint_name   = cu.constraint_name and 
                    tc.table_name        = cu.table_name
    
    where   cu.table_name = 'table_name_goes_here'
    
    order by constraint_name, ordinal_position
    

提交回复
热议问题