2012-05-15 48 views
0

我有很多數據庫,外鍵(非正式)字段名稱和主鍵字段名稱對於以下代碼中可見的示例是相同的。在各種SQL語法中創建自動關係

CREATE TABLE Customer(
    CustomerId int PRIMARY, 
    CustomerName varchar(200), 
... 
) 
CREATE TABLE Invoice(
     InvoiceID int PRIMARY KEY, 
     InvoiceType int , 
     CustomerID int) 
CREATE TABLE InvoiceDet(
     InvoiceDetId int PRIMARY KEY, 
     InvoiceId int ...) 

我想要一個程序(或腳本),上面寫着我的表,列和創造的應該生產關係的外鍵references.samples:Customer.CustomerId<=>Invoice.CustomerIDInvoiceDet.InvoiceId<=>Invoice.InvoiceId

+4

我們是玩輪盤賭的DBMS?選擇一個... –

+1

你的意思是什麼*自動關係*?我不明白朮語 –

+0

你想要一個程序來讀取你的表並自動創建外鍵引用嗎? –

回答

2

這是一個巨大的任務創建這樣的自動化腳本,特別是對於你提到的所有數據庫。你應該考慮聘請一些具有Perl/Python知識的優秀DBA爲你做這件事。

支票(中鍵和類型的列的列數不交叉檢查)的最小量,下面可能是PostgreSQL中concept proof

WITH colnames(oid,colnum,colname) AS (
    SELECT a.attrelid AS oid, a.attnum AS colnum, a.attname AS colname 
     FROM pg_attribute a WHERE a.attnum > 0 AND NOT a.attisdropped), 
pkcols(oid,colnum) AS (
    SELECT c.conrelid AS oid, unnest(c.conkey) 
     FROM pg_constraint c 
    WHERE contype = 'p'), 
pks(oid,colnum,colname) AS (
    SELECT pkc.oid, pkc.colnum, cn.colname 
     FROM pkcols pkc 
     JOIN colnames cn ON pkc.oid = cn.oid AND pkc.colnum = cn.colnum), 
pktabs AS (
    SELECT t.oid AS oid, n.nspname AS sname, t.relname AS tname, 
      pks.colnum AS colnum, pks.colname AS colname 
     FROM pg_class t 
     JOIN pg_namespace n ON n.oid = t.relnamespace 
     JOIN pks ON pks.oid = t.oid 
    WHERE t.relkind = 'r'), 
coltabs AS (
    SELECT t.oid AS oid, n.nspname AS sname, t.relname AS tname, 
      cn.colnum AS colnum, cn.colname AS colname 
     FROM pg_class t 
     JOIN pg_namespace n ON n.oid = t.relnamespace 
     JOIN colnames cn ON cn.oid = t.oid 
    WHERE t.relkind = 'r') 
SELECT 'ALTER TABLE '||quote_ident(ct.sname)||'.'||quote_ident(ct.tname)|| 
     ' ADD FOREIGN KEY ('||string_agg(quote_ident(pk.colname),',')|| 
     ') REFERENCES '|| 
     quote_ident(pk.sname)||'.'||quote_ident(pk.tname)||' ('|| 
     string_agg(quote_ident(pk.colname),',')||');' 
    FROM pktabs pk 
    JOIN coltabs ct ON pk.oid != ct.oid AND pk.colname = ct.colname 
GROUP BY pk.sname,pk.tname,ct.sname,ct.tname;