Question

I am having a hard time making my PL/SQL code work. I have a constraint that makes sure 5 digits have been input. The constraint works for any number that does not use a 0 first. Example 0, 1, 2, 33, 401 work but 01, 02, 004 do not work. How can I make it so that I can input numbers such as 00009?

CREATE TABLE table1
(
 id NUMBER(5)
    CONSTRAINT idconstraint
        CHECK (REGEXP_LIKE(id, '[0-9][0-9][0-9][0-9][0-9]'))
);


INSERT INTO table1
VALUES ('00009');
Was it helpful?

Solution

You seem to have the wrong constraint or the wrong data type. If you want leading zeros, use varchar2() or char(). Because you seem to want a fixed length string, try this:

CREATE TABLE table1 (
    id CHAR(5)
        CONSTRAINT idconstraint
            CHECK (REGEXP_LIKE(id, '[0-9][0-9][0-9][0-9][0-9]'))
);

Your problem is that the field is declared as a number. The input string is converted to a number, then back to a string. It loses the leading 0's in the process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top