ProgramingTip

Postgresql에서 이름으로 제약 조건 삭제

bestdevel 2020. 11. 1. 18:27
반응형

Postgresql에서 이름으로 제약 조건 삭제


이름 만 아는 것만으로 Postgresql에서 제약 조건 이름을 선택해야합니까? 펼쳐서 자동 생성되는 제약 조건 목록이 있습니다. 테이블 이름을 모르고 제약 조건 이름 만 삭제해야합니다.


다음 쿼리를 실행하여 테이블 이름을 검색해야합니다.

SELECT *
FROM information_schema.constraint_table_usage
WHERE table_name = 'your_table'

또는 pg_constraint이 정보를 검색 하는 사용할 수 있습니다.

select n.nspname as schema_name,
       t.relname as table_name,
       c.conname as constraint_name
from pg_constraint c
  join pg_class t on c.conrelid = t.oid
  join pg_namespace n on t.relnamespace = n.oid
where t.relname = 'your_table_name';

그런 다음 ALTER TABLE 문을 사용할 수 있습니다.

ALTER TABLE your_table DROP CONSTRAINT constraint_name;

물론 쿼리가 완전한 alter 문을 반환 할 수 있습니다.

SELECT 'ALTER TABLE '||table_name||' DROP CONSTRAINT '||constraint_name||';'
FROM information_schema.constraint_table_usage
WHERE table_name in ('your_table', 'other_table')

동일한 테이블에 여러 스키마가있는 경우 WHERE 절 (및 ALTER 문)에 table_schema를 포함하는 것을 포함합니다.


9.x의 PG에서 DO 문을 사용하여 사용할 수 있습니다. a_horse_with_no_name이 한 일을 수행하되 DO 문에 적용하십시오.

DO $$DECLARE r record;
    BEGIN
        FOR r IN SELECT table_name,constraint_name
                 FROM information_schema.constraint_table_usage
                 WHERE table_name IN ('your_table', 'other_table')
        LOOP
            EXECUTE 'ALTER TABLE ' || quote_ident(r.table_name)|| ' DROP CONSTRAINT '|| quote_ident(r.constraint_name) || ';';
        END LOOP;
    END$$;

-올바른 외래 키 제약 조건 삭제

ALTER TABLE affiliations
DROP CONSTRAINT affiliations_organization_id_fkey;

노트 :

소속-> 테이블 이름

affiliations_organization_id_fkey-> 제약 이름

참고 URL : https://stackoverflow.com/questions/5273717/drop-constraint-by-name-in-postgresql

반응형