Delete a child and a parent row with one SQL script

前端 未结 7 615
执念已碎
执念已碎 2021-01-04 00:30

Instead of deleting the child row and then writing another sql statement to delete the parent row I wanted to use one statement which will do both. FYI: we use Oracle databa

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 00:36

    In case it helps anyone else, I just wrote a PLSQL script to do this for all foreign key constraints in a table with some help from this Stackoverflow question. Hope it helps.

    DECLARE
      CURSOR constraint_cursor IS SELECT *
                                  FROM (SELECT a.table_name,
                                               a.constraint_name,
                                               a.column_name,
                                               c_pk.table_name r_table_name,
                                               b.column_name   r_column_name
                                        FROM user_cons_columns a
                                               JOIN user_constraints c ON a.owner = c.owner
                                                                            AND a.constraint_name = c.constraint_name
                                               JOIN user_constraints c_pk ON c.r_owner = c_pk.owner
                                                                               AND
                                                                             c.r_constraint_name = c_pk.constraint_name
                                               JOIN user_cons_columns b ON C_PK.owner = b.owner
                                                                             AND
                                                                           C_PK.CONSTRAINT_NAME = b.constraint_name AND
                                                                           b.POSITION = a.POSITION
                                        WHERE c.constraint_type = 'R'
                                          and c_pk.owner = 'YOUR SCHEMA HERE') tbl;
      sql_statement VARCHAR2(2048) := NULL;
      tab_row       constraint_cursor%rowtype;
    BEGIN
      OPEN constraint_cursor;
      FOR i in 1..80 LOOP
        FETCH constraint_cursor into tab_row;
        EXECUTE IMMEDIATE 'ALTER table ' || tab_row.table_name || ' drop constraint ' || tab_row.constraint_name;
        EXECUTE IMMEDIATE 'ALTER table ' || tab_row.table_name || ' add constraint ' || tab_row.constraint_name || ' FOREIGN KEY (' ||
        tab_row.column_name || ') references ' || tab_row.r_table_name || '(' || tab_row.r_column_name || ') ON DELETE CASCADE ';
      end loop;
      close constraint_cursor;
    end;
    

提交回复
热议问题