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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With