使用Postgres中的数据字典表生成父表字段

时间:2019-01-23 18:06:19

标签: postgresql postgresql-9.3

我们如何使用数据字典表捕获主键表及其用作参考的外键的字段,

下面是代码

WITH PRIMARY_REF AS
(select string_agg(cu.column_name,',') COL1_NAME, tc.table_name tab_name
from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU,
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
where CU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME 
and   TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
and UPPER(TC.CONSTRAINT_SCHEMA) = 'SSP2_PCAT'
group by tab_name order by tc.table_name),
FOREIGN_REF AS
(select string_agg(U.column_name,',') COL2_NAME, TC.TABLE_NAME 
from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE U, 
 INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK,
 INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
where U.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
and   FK.CONSTRAINT_NAME = TC.CONSTRAINT_NAME 
--and   TC.TABLE_NAME = U.TABLE_NAME
and   TC.CONSTRAINT_TYPE = 'FOREIGN KEY'
and UPPER(TC.CONSTRAINT_SCHEMA) = 'SSP2_PCAT'
--and   UPPER(TC.TABLE_NAME) = 'ADDITIONAL_RULES'   
group by TC.TABLE_NAME) 
SELECT DISTINCT 'ALTER TABLE'||' SSP2_PCAT.'||cs.TABLE_NAME || 
' ADD CONSTRAINT ' ||rc.CONSTRAINT_NAME ||
' FOREIGN KEY ' ||COL2_NAME ||
' REFERENCES '||' SSP2_PCAT.'||TAB_NAME || ' (' || COL1_NAME || ') ' || ' 
ON UPDATE ' || rc.UPDATE_RULE || ' ON DELETE ' || rc.DELETE_RULE ||';'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC, 
INFORMATION_SCHEMA.TABLE_CONSTRAINTS CS, 
PRIMARY_REF,
FOREIGN_REF
WHERE 
cs.TABLE_NAME = FOREIGN_REF.TABLE_NAME AND
FOREIGN_REF.TABLE_NAME = PRIMARY_REF.TAB_NAME AND 
RC.CONSTRAINT_NAME = CS.CONSTRAINT_NAME AND
UPPER(cs.CONSTRAINT_SCHEMA) = 'SSP2_PCAT'
AND UPPER(cs.TABLE_NAME) = 'ADDITIONAL_RULES';

预期结果是:

ALTER TABLE ssp2_pcat.additional_rules ADD CONSTRAINT fk1_addnl_rules FOREIGN KEY (offer_id, promotion_id) REFERENCES ssp2_pcat.promotion_offer (offer_id, promotion_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION;

上面的查询结果是:

ALTER TABLE SSP2_PCAT.additional_rules ADD CONSTRAINT fk1_addnl_rules FOREIGN KEY (promotion_id,offer_id) REFERENCES SSP2_PCAT.**additional_rules** **(offer_id,promotion_id,channel,rule_grp_cd,rule_subgp_cd,rule_type, rule_start_date,rule_value,addnl_ruleid,promotion_id,offer_id)** ON UPDATE NO ACTION ON DELETE NO ACTION;

因此,它没有返回正确的父表和用作 引用外键,似乎我缺少一些数据字典表或过滤条件,截至目前,我只用一个表测试一次脚本,如果成功,我可以使用in子句在同一脚本中包含约150个表。

任何帮助绝对感激! 谢谢您的时间

0 个答案:

没有答案