问题
I'm using an Informix database. I have added some foreign keys to a table without giving them a name e.g.
ALTER TABLE myreport
ADD CONSTRAINT FOREIGN KEY (rid) REFERENCES report(id),
ADD CONSTRAINT FOREIGN KEY (uid) REFERENCES user(id);
Now I want to delete the foreign key between uid
and id
of user
table.
I can get the name of the constraints on the table using the following:
SELECT constrname
FROM sysconstraints
WHERE tabid = (SELECT tabid FROM systables WHERE tabname = 'myreport');
which gives following output:
constrname u169_201
constrname n169_202
constrname n169_203
constrname n169_204
constrname n169_205
constrname n169_206
constrname n169_207
constrname r169_276
constrname r169_277
I don't know which constraint belongs to the foreign key between uid
and id
of user
table.
回答1:
Try using the sysreferences
catalog table. Something like this should give you the information you need:
SELECT
c_a.constrname AS Constraint_name
, t_a.tabname AS ForeignKey_table
, i_a.idxname AS ForeignKey_index
, t_b.tabname AS PrimaryKey_table
, i_b.idxname AS PrimaryKey_index
FROM
sysreferences AS r
INNER JOIN sysconstraints AS c_a
ON
r.constrid = c_a.constrid
INNER JOIN systables AS t_a
ON
c_a.tabid = t_a.tabid
INNER JOIN systables AS t_b
ON
r.ptabid = t_b.tabid
INNER JOIN sysindexes AS i_a
ON
c_a.idxname = i_a.idxname
INNER JOIN sysconstraints AS c_b
ON
r.primary = c_b.constrid
INNER JOIN sysindexes AS i_b
ON
c_b.idxname = i_b.idxname
WHERE
t_a.tabname = 'YOUR_TABLE_HERE';
回答2:
I tried following it worked:
CREATE PROCEDURE INFORMIX.REMOVE_FK()
DEFINE tmpvr varchar(250);
FOREACH cur1 FOR select b.constrname into tmpvr
from systables a, sysconstraints b, sysindexes c, syscolumns d
WHERE a.tabname = 'myreport' AND (d.colname='uid' or d.colname='rid')
AND b.tabid = a.tabid AND c.idxname = b.idxname AND d.tabid = a.tabid AND (
d.colno = c.part1 or d.colno = c.part2 or d.colno = c.part3 or d.colno = c.part4 or
d.colno = c.part5 or d.colno = c.part6 or d.colno = c.part7 or d.colno = c.part8 or
d.colno = c.part9 or d.colno = c.part10 or d.colno = c.part11 or d.colno = c.part12 or
d.colno = c.part13 or d.colno = c.part14 or d.colno = c.part15 or d.colno = c.part16
)
EXECUTE IMMEDIATE 'ALTER TABLE myreport DROP CONSTRAINT (' || tmpvr || ')';
END FOREACH
END PROCEDURE;
EXECUTE PROCEDURE INFORMIX.REMOVE_FK();
DROP PROCEDURE INFORMIX.REMOVE_FK();
来源:https://stackoverflow.com/questions/46466980/drop-a-foreign-key-constraint-between-columns-of-two-tables-without-knowing-the