查找数据库中的所有表由primaryKey

时间:2017-06-05 14:11:33

标签: sql

我正在搜索可以通过特定数据库上指定的键/键名检索所有表的查询。 像这样:

SELECT table_name 
FROM   information_Schema.columns 
WHERE  column_name='ID_UNICO' 
AND    Constraint_Type = 'PRIMARY KEY'

我一直在寻找,我能找到的最好的是:

SELECT 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'
    AND Col.Table_Name = '<your table name>'

这将检索特定表的PK,我想找到table_name BY PK名称。

SELECT table_name 
FROM   information_Schema.columns 
WHERE  column_name='ID_UNICO' 
and    ordinal_position = 1; 

也找到了这个,但是这给了我表格的第一列,它并不能确保它是PK。

无法找到任何重复。

3 个答案:

答案 0 :(得分:2)

这对你有用吗?

DECLARE @ColName AS VARCHAR(MAX)
SET @ColName = 'CourseId'
SELECT
    TABLE_NAME
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    COLUMNPROPERTY(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    AND COLUMN_NAME = @ColName

答案 1 :(得分:1)

在这里,将TABLE_CONSTRAINTS连接到CONSTRAINT_COLUMN_USAGE以将约束名称绑定到列,然后返回TABLE_NAME:

SELECT CCU.COLUMN_NAME, 
       CONS.TABLE_NAME 
FROM   INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CCU 
       JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS CONS 
         ON CONS.CONSTRAINT_NAME = CCU.CONSTRAINT_NAME 
WHERE  CONS.CONSTRAINT_TYPE = 'PRIMARY KEY' 
       AND CCU.COLUMN_NAME = 'ID_UNICO' 

答案 2 :(得分:1)

您可以使用此查询。将“YOUR_COLUMN_NAME”替换为您的主键列名称。

SELECT Table_Name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
and COLUMN_NAME ='YOUR_COLUMN_NAME'