program tip

ALTER TABLE 문에 'ON DELETE CASCADE'를 추가하는 방법

radiobox 2020. 8. 7. 08:16
반응형

ALTER TABLE 문에 'ON DELETE CASCADE'를 추가하는 방법


내 테이블에 외래 키 제약 조건이 있습니다. ON DELETE CASCADE를 추가하고 싶습니다.

나는 이것을 시도했다 :

child_table_name 테이블 변경
  제약 조건 fk_name 수정
  외래 키 (child_column_name)
  계단식 삭제에서 parent_table_name (parent_column_name)을 참조합니다.

작동하지 않습니다.

편집 :
외래 키가 이미 존재하며 외래 키 열에 데이터가 있습니다.

문을 실행 한 후 나타나는 오류 메시지 :

ORA-02275 : 이러한 참조 제약이 이미 테이블에 존재합니다

ON DELETE CASCADE이미 존재하는 제약 에는 추가 할 수 없습니다 . 당신은 제약을 drop받아야만 할 것 create입니다. 문서 것을 보여 MODIFY CONSTRAINT조항 만 수정할 수 있습니다 제약의 상태 (예 : ENABLED/DISABLED...).


먼저 drop외국 키와 위의 명령 시도는 넣어 add constraint대신 modify constraint. 이제 이것은 명령입니다.

ALTER TABLE child_table_name 
  ADD CONSTRAINT fk_name 
  FOREIGN KEY (child_column_name) 
  REFERENCES parent_table_name(parent_column_name) 
  ON DELETE CASCADE;

이 PL * SQL은 삭제 캐스케이드가없는 각 제약 조건을 삭제하고 삭제 캐스케이드로 다시 생성하는 스크립트를 DBMS_OUTPUT에 기록합니다.

참고 :이 스크립트의 출력을 실행하는 것은 사용자의 책임입니다. 결과 스크립트를 읽고 실행하기 전에 편집하는 것이 가장 좋습니다.

DECLARE
      CURSOR consCols (theCons VARCHAR2, theOwner VARCHAR2) IS
        select * from user_cons_columns
            where constraint_name = theCons and owner = theOwner
            order by position;
      firstCol BOOLEAN := TRUE;
    begin
        -- For each constraint
        FOR cons IN (select * from user_constraints
            where delete_rule = 'NO ACTION'
            and constraint_name not like '%MODIFIED_BY_FK'  -- these constraints we do not want delete cascade
            and constraint_name not like '%CREATED_BY_FK'
            order by table_name)
        LOOP
            -- Drop the constraint
            DBMS_OUTPUT.PUT_LINE('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' DROP CONSTRAINT ' || cons.CONSTRAINT_NAME || ';');
            -- Re-create the constraint
            DBMS_OUTPUT.PUT('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' ADD CONSTRAINT ' || cons.CONSTRAINT_NAME 
                                        || ' FOREIGN KEY (');
            firstCol := TRUE;
            -- For each referencing column
            FOR consCol IN consCols(cons.CONSTRAINT_NAME, cons.OWNER)
            LOOP
                IF(firstCol) THEN
                    firstCol := FALSE;
                ELSE
                    DBMS_OUTPUT.PUT(',');
                END IF;
                DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
            END LOOP;                                    

            DBMS_OUTPUT.PUT(') REFERENCES ');

            firstCol := TRUE;
            -- For each referenced column
            FOR consCol IN consCols(cons.R_CONSTRAINT_NAME, cons.R_OWNER)
            LOOP
                IF(firstCol) THEN
                    DBMS_OUTPUT.PUT(consCol.OWNER);
                    DBMS_OUTPUT.PUT('.');
                    DBMS_OUTPUT.PUT(consCol.TABLE_NAME);        -- This seems a bit of a kluge.
                    DBMS_OUTPUT.PUT(' (');
                    firstCol := FALSE;
                ELSE
                    DBMS_OUTPUT.PUT(',');
                END IF;
                DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
            END LOOP;                                    

            DBMS_OUTPUT.PUT_LINE(')  ON DELETE CASCADE  ENABLE VALIDATE;');
        END LOOP;
    end;

앞에서 설명한대로 :

ALTER TABLE TABLEName
drop CONSTRAINT FK_CONSTRAINTNAME;

ALTER TABLE TABLENAME
ADD CONSTRAINT FK_CONSTRAINTNAME
    FOREIGN KEY (FId)
    REFERENCES OTHERTABLE
        (Id)
    ON DELETE CASCADE ON UPDATE NO ACTION;

보시다시피 명령을 분리해야하며 먼저 드롭 한 다음 추가해야합니다.


MYSQL 사용자를위한 답변 :

ALTER TABLE ChildTableName 
DROP FOREIGN KEY `fk_table`;
ALTER TABLE ChildTableName 
ADD CONSTRAINT `fk_t1_t2_tt`
  FOREIGN KEY (`parentTable`)
  REFERENCES parentTable (`columnName`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

MySQL을 사용하는 모든 사람 :

당신은 당신에 머리를하면 PHPMYADMIN당신이해야 할 클릭, 당신은 업데이트 할 외래 키가있는 테이블에 웹 페이지 및 탐색 Relational view에있는 Structure탭과 변경 On delete에 선택 메뉴 옵션을 Cascade.

아래에 표시된 이미지 :

여기에 이미지 설명을 입력하십시오


Here is an handy solution! I'm using SQL Server 2008 R2.

As you want to modify the FK constraint by adding ON DELETE/UPDATE CASCADE, follow these steps:

NUMBER 1:

Right click on the constraint and click to Modify

여기에 이미지 설명을 입력하십시오

NUMBER 2:

Choose your constraint on the left side (if there are more than one). Then on the right side, collapse "INSERT And UPDATE Specification" point and specify the actions on Delete Rule or Update Rule row to suit your need. After that, close the dialog box.

여기에 이미지 설명을 입력하십시오

NUMBER 3:

The final step is to save theses modifications (of course!)

여기에 이미지 설명을 입력하십시오

PS: It's saved me from a bunch of work as I want to modify a primary key referenced in another table.


If you want to change a foreign key without dropping it you can do:

ALTER TABLE child_table_name  WITH CHECK ADD FOREIGN KEY(child_column_name)
REFERENCES parent_table_name (parent_column_name) ON DELETE CASCADE

ALTER TABLE `tbl_celebrity_rows` ADD CONSTRAINT `tbl_celebrity_rows_ibfk_1` FOREIGN KEY (`celebrity_id`) 
REFERENCES `tbl_celebrities`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;

참고 URL : https://stackoverflow.com/questions/1571581/how-to-add-on-delete-cascade-in-alter-table-statement

반응형