7

i want to add Constraint in table but before adding i have to check is that Constraint existing in table or not like

IF NOT EXISTS(some condition)

ADD CONSTRAINT CHK_DATES_VALID
CHECK ((DATE_NORMAL != 'n' AND DATE_NORMAL != 'N') OR
       (DATE_SCHEDULED != 'n' AND DATE_SCHEDULED != 'N') OR
       (DATE_WINDOW != 'n' AND DATE_WINDOW != 'N'));

before adding constraint 'CHK_DATES_VALID' i need to check is that constrain existing or not please guide me to make this condation .

1 Answer 1

8

You cannot use IF like that.

You need to check the system view ALL_CONSTRAINTS in order to find out if the constraint if already defined:

DECLARE 
  num_rows integer;
BEGIN
   SELECT count(*)
      INTO num_rows
   FROM all_constraints
   WHERE constraint_name = 'CHK_DATES_VALID';

   IF num_rows = 0 THEN 
       EXECUTE IMMEDIATE 'ALTER TABLE the_table 
         ADD CONSTRAINT CHK_DATES_VALID
         CHECK ((to_upper(DATE_NORMAL) != ''N'') OR
                (to_upper(DATE_SCHEDULED) != ''N'') OR
                (to_upper(DATE_WINDOW) != ''N''))';
   END IF;
END;
/

The EXECUTE IMMEDIATE is necessary because you cannot run DDL directly in a PL/SQL block.

A much easier solution would be to simply add the constraint and catch any error that occurs.

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

3 Comments

hi its taking time because i have thousand of table and thousand of constraints , plz tell me any other soln
There is no other solution to add a constraint
Thanks for explaining why execute immediate is necessary.

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.