SQL:检查主键是否为外键

时间:2013-09-02 12:48:31

标签: sql sql-server sql-server-2008 database-schema

如果它也是来自信息模式的外键,我想提取表的名称主键列 像两张桌子一样:

Student 
std_id  std_name

PHDstudent
std_id   reaserchfield

PHDstudent中的std_id是同时引用Student表的主键和外键。

3 个答案:

答案 0 :(得分:2)

运行此查询

SELECT Tab.TABLE_NAME, Col.Column_Name from 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE 
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'PRIMARY KEY '
INTERSECT
SELECT Tab.TABLE_NAME, Col.Column_Name from 
    INFORMATION_SCHEMA.TABLE_CONSTRAINTS Tab, 
    INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE Col 
WHERE 
    Col.Constraint_Name = Tab.Constraint_Name
    AND Col.Table_Name = Tab.Table_Name
    AND Constraint_Type = 'FOREIGN KEY '

答案 1 :(得分:0)

SELECT s.std_id FROM Student s 
INNER JOIN PHDstudent p 
ON s.std_id = p.std_id 

阅读INNER JOINS

答案 2 :(得分:0)

我认为您询问的是主键列名称,而不应该使用下面的查询,它会为您提供主键列名称.....

<强> SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1 AND table_name = 'PHDstudent'