0

I want to drop constraint with the name unknown so I use the following code:

EXECUTE 'ALTER TABLE public."IntravenousTherapyAppointment" DROP CONSTRAINT '||fk_Name||';';

The problem is that fk_Name ends with '~' so I get syntax error.

The full code:

DO $$
DECLARE fk_Name TEXT;
BEGIN
    fk_Name := (SELECT
                tc.constraint_name
                FROM
                information_schema.table_constraints AS tc
                JOIN information_schema.key_column_usage AS kcu
                ON tc.constraint_name = kcu.constraint_name
                AND tc.table_schema = kcu.table_schema
                JOIN information_schema.constraint_column_usage AS ccu
                ON ccu.constraint_name = tc.constraint_name
                AND ccu.table_schema = tc.table_schema
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='IntravenousTherapyAppointment' AND ccu.table_name='MedicamentMeasurementUnit');
    IF fk_Name IS NOT NULL THEN
        EXECUTE 'ALTER TABLE public."IntravenousTherapyAppointment" DROP CONSTRAINT '||fk_Name||';';
    END IF;
END $$;

1 Answer 1

1

this should fix your problem:

DO $$
DECLARE fk_Name TEXT;
BEGIN
    fk_Name := (SELECT
                tc.constraint_name
                FROM
                information_schema.table_constraints AS tc
                JOIN information_schema.key_column_usage AS kcu
                ON tc.constraint_name = kcu.constraint_name
                AND tc.table_schema = kcu.table_schema
                JOIN information_schema.constraint_column_usage AS ccu
                ON ccu.constraint_name = tc.constraint_name
                AND ccu.table_schema = tc.table_schema
                WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='IntravenousTherapyAppointment' AND ccu.table_name='MedicamentMeasurementUnit');
    IF fk_Name IS NOT NULL THEN
        EXECUTE 'ALTER TABLE public."IntravenousTherapyAppointment" DROP CONSTRAINT "'||fk_Name||'";';
    END IF;
END $$;

P.S: Be careful while handling the objects/constraints having double quoted names.

Sign up to request clarification or add additional context in comments.

1 Comment

I had problems with that type of varible assignment in my posgres DB. I needed to it similar to oracle with: SELECT constraint_name INTO fk_Name. Also a good idea in PL scripts is to use the RAISE NOTICE 'SOME text to be logged out'; to see where the script is navigating into.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.