local function inside PL/SQL script

user1630809 picture user1630809 · Feb 18, 2014 · Viewed 24.1k times · Source

I'm trying to execute this code in Oracle 10 SQL Developer:

FUNCTION is_valid_date (p_val in VARCHAR2, p_format IN VARCHAR2 ) 
RETURN numeric IS
    l_date VARCHAR2(100);
BEGIN
    l_date := TO_date( p_val, p_format );
    RETURN 1;
EXCEPTION
    WHEN OTHERS THEN
        RETURN 0;
END is_valid_date;


BEGIN
DBMS_OUTPUT.PUT_LINE(is_valid_date('20120101', 'YYYYMMDD' )); 
END;

but I get a generic error without any specific Oracle code, as if it is a syntax problem.

I need to check if a date is valid and, as there is no Oracle built in function for that, I have defined it inside my script (I don't want it to be global or stored somewhere).

Edit:

I have found a solution on an oracle forum using oracle regexp, instead of a function. My script is:

BEGIN

select * from mytable where not REGEXP_LIKE(mydatefield, '(((0[1-9]|[12]\d|3[01])\.(0[13578]|1[02])\.((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\.(0[13456789]|1[012])\.((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\.02\.((19|[2-9]\d)\d{2}))|(29\.02\.((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))')

END;

where mydatefield is in the format DD.MM.YYYY

Answer

Alex Poole picture Alex Poole · Feb 18, 2014

If that's your entire script, you're missing the DECLARE keyword at the start of your anonymous block:

DECLARE
    FUNCTION is_valid_date (p_val in VARCHAR2, p_format IN VARCHAR2 ) 
    RETURN numeric IS
        l_date VARCHAR2(100);
    BEGIN
        l_date := TO_date( p_val, p_format );
        RETURN 1;
    EXCEPTION
        WHEN OTHERS THEN
            RETURN 0;
    END is_valid_date;

BEGIN
    DBMS_OUTPUT.PUT_LINE(is_valid_date('20120101', 'YYYYMMDD' )); 
END;
/

anonymous block completed
1

Without that you'll get a series of errors starting with

Error starting at line : 1 in command -
FUNCTION is_valid_date (p_val in VARCHAR2, p_format IN VARCHAR2 )
Error report -
Unknown Command

... which I imagine is the 'generic error' you referred to.