2013-12-10 125 views
0

是否可以检查现有约束的特定值?检查SQL约束值

例如,我想检查一个FOREIGN KEY约束是否为ON DELETE SET NULLON DELETE NO ACTION

我只找到解决方案,如果一个约束是根本存在的,但不是一个特定的值。

+0

工作,你为什么与'mysql' **和**'postgres'标签呢? –

+0

因为这是一个应该与这两个数据库一起运行的应用程序。 –

回答

1

由于开发无效居民建议在their answer

简单的方式来获得外键指定表:

SELECT 
    `column_name`, 
    `referenced_table_schema` AS foreign_db, 
    `referenced_table_name` AS foreign_table, 
    `referenced_column_name` AS foreign_column 
FROM 
    `information_schema`.`KEY_COLUMN_USAGE` 
WHERE 
    `constraint_schema` = SCHEMA() 
AND 
    `table_name` = 'your-table-name-here' 
AND 
    `referenced_column_name` IS NOT NULL 
ORDER BY 
    `column_name`; 

或者另一种方式,suggested by Lo Sauer是:

SELECT * FROM information_schema.table_constraints 
     WHERE table_schema = 'dbname' AND table_name='mytable'; 
+0

这是在MySQL和pgsql中工作吗? –

+0

呃,试试你的数据库 – sergio

+0

@MarcelBalzer:不会因为非标准的反引号,不存在的'schema()'函数和'information_schema'表之间的差异两个DBMS。 –

1

对于Postgres,这将是类似于:

select tc.table_schema||'.'||tc.table_name as referencing_table, 
     ctu.table_schema||'.'||ctu.table_name as referenced_table_name, 
     rc.update_rule, 
     rc.delete_rule 
from information_schema.table_constraints tc 
    join information_schema.referential_constraints rc 
    on tc.constraint_catalog = rc.constraint_catalog 
    and tc.constraint_schema = rc.constraint_schema 
    and tc.constraint_name = rc.constraint_name 
    join information_schema.constraint_table_usage ctu 
    on ctu.constraint_catalog = rc.unique_constraint_catalog 
    and ctu.constraint_schema = rc.unique_constraint_schema 
    and ctu.constraint_name = rc.unique_constraint_name 
where tc.table_name = 'foobar' 
    and tc.table_schema = 'public' 
    and tc.constraint_type = 'FOREIGN KEY' 

但是,这不会对MySQL的