Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check before adding Constraint in table (oracle)

Tags:

oracle11g

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 .

like image 228
jaiswal Avatar asked May 28 '11 19:05

jaiswal


People also ask

How do I add a check constraint to an existing table in Oracle?

The syntax for creating a check constraint in an ALTER TABLE statement in Oracle is: ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]; The DISABLE keyword is optional.

What will happen if you are trying to add a check constraint to a table?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.

What is constraint type check in Oracle?

An Oracle check constraint allows you to enforce domain integrity by limiting the values accepted by one or more columns. To create a check constraint, you define a logical expression that returns true or false. Oracle uses this expression to validate the data that is being inserted or updated.


1 Answers

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.

like image 107
a_horse_with_no_name Avatar answered Nov 16 '22 14:11

a_horse_with_no_name