How to write the code in Oracle SQL
(like \'CCYYMMDD\'
into 102
)?
If someone will enter the date in the frontend, the value should return
You can verify that a string fits a date format like this:
create or replace function is_CCYYMMDD
(p_str in varchar2)
return boolean
is
rv boolean;
dt date;
begin
begin
dt := to_date(p_str, 'YYYYMMDD');
dt := to_date('2000' || substr(p_str, 5), 'YYYYMMDD');
rv := true;
exception
when others then
rv := false;
end;
return rv;
end;
The first to_date()
just checks that the whole string is a valid date. The second to_date()
checks that the second half of the string is a valid month and day combo. This partly addresses @MTO observations about the problems of enforcing a strict format when some strings can fit more than one format.
Note that it is perfectly possible to have valid dates which pass this test despite being ambiguous e.g. is 20111012
in 'YYYYMMDD'
or 'DDMMYYYY'
? There is no way to be sure unless you enforce strict date formatting in the front-end input by using a date picker widget or separate input boxes for year, month and day.
why you pass '2000' in this query?
The second check verifies that the last four characters are valid as month and day. Whenever we do this sort of test we run into the problem of leap years. If we just apply to_date(str, 'MMDD')
Oracle will default the year to the current year: the snag is 2018029
is not a valid date even though the original input of 20160229
is valid. My function avoids this by fixing the year element to 2000, which was a leap year.
Incidentally, if you want to use this function in SQL you'll need to change the return datatype to varchar2 (Y/N flag) or a number (1/0) because SQL doesn't support Booolean.