PL/SQL check date is valid - oracle

If I have a date format DDMM in PL/SQL and I want to validate it. What is the correct way to do it?
DD is the day and MM is the moth.
For an example:
0208 - is a valid date
3209 - is not a valid date
0113 - is not a valid date.

You could write a function like this one, for instance:
create or replace function is_valid(p_val in varchar2)
return number
is
not_a_valid_day exception;
not_a_valid_month exception;
pragma exception_init(not_a_valid_day, -1847);
pragma exception_init(not_a_valid_month, -1843);
l_date date;
begin
l_date := to_date(p_val, 'ddmm');
return 1;
exception
when not_a_valid_day or not_a_valid_month
then return 0;
end;
SQL> with test_dates(dt) as(
2 select '0208' from dual union all
3 select '3209' from dual union all
4 select '0113' from dual
5 )
6 select dt, is_valid(dt) as valid
7 from test_dates
8 /
DT VALID
---- ----------
0208 1
3209 0
0113 0

to_date raises an exception if its input parameter is not a valid date. So you can do something like:
declare
x date;
begin
x := to_date('3210', 'DDMM'); -- Will raise ORA-1847
x := to_date('0113', 'DDMM'); -- Will raise ORA-1843
exception
when others then
if sqlcode in (-1843, -1847) then
dbms_output.put_line('Invalid Date!');
null;
else
raise;
end if;
end;

Related

Can not assign value to an IN OUT parameter

procedure check_startDate_is_grower_than_last_foo(startDate IN OUT DATE) as
last_foo_tsp DATE;
begin
select max(version_tsp) into last_foo_tsp from foo;
if startDate <= last_foo_tsp then
if trunc(startDate) = trunc(last_foo_tsp) then
startDate := (last_foo_tsp + 1/86400); -- +1 seg
else
raise_application_error(-20001, 'Blabla');
end if;
end if;
end;
I get an error:
PLS-00363: expression 'STARTDATE' cannot be used as an assignment target
What I'm doing wrong?
I don't know what you did wrong, because - it works for me.
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';
Session altered.
SQL> select * from foo;
VERSION_TSP
-------------------
15.02.2022 00:00:00
SQL> create or replace
2 procedure p_check (startDate IN OUT DATE) as
3 last_foo_tsp DATE;
4 begin
5 select max(version_tsp) into last_foo_tsp from foo;
6 if startDate <= last_foo_tsp then
7 if trunc(startDate) = trunc(last_foo_tsp) then
8 startDate := (last_foo_tsp + 1/86400); -- +1 seg
9 else
10 raise_application_error(-20001, 'Blabla');
11 end if;
12 end if;
13 end;
14 /
Procedure created.
Testing:
SQL> set serveroutput on
SQL> declare
2 l_datum date := date '2022-02-15';
3 begin
4 p_check (l_datum);
5 dbms_output.put_line('result = ' || l_datum);
6 end;
7 /
result = 15.02.2022 00:00:01
PL/SQL procedure successfully completed.
SQL>

pipelined function with if statement

I'd like to create a function to retrieve valid years for each record. I've got columns valid_from and valid_to in table.
For example valid_from = 2018-04-30 and valid_to = 2020-06-30; function should result three values: 2018, 2019, 2020.
I created a type and a function but it isn't working at all ...
create or replace type t_years is table of varchar2(4);
create or replace function func_year(d_from date, d_to date) return t_years pipelined
is
v_date date := '21/12/31 00:00:00';
max_date date := '99/12/30 00:00:00';
begin
for x in 1..2 loop
if d_from <= add_months(v_date,-1*12) AND (add_months(d_to,-1*12) >= v_date OR add_months(d_to,-1*12) = max_date) then return '2020';
elsif d_from <= add_months(v_date,-2*12) AND (add_months(d_to,-2*12) >= v_date OR add_months(d_to,-2*12) = max_date) then return '2019';
end if;
pipe row(x);
end loop;
return;
end;
Here's how:
SQL> CREATE OR REPLACE TYPE t_years IS TABLE OF VARCHAR2 (4);
2 /
Type created.
SQL> CREATE OR REPLACE FUNCTION func_year (d_from IN DATE, d_to IN DATE)
2 RETURN t_years
3 PIPELINED
4 IS
5 BEGIN
6 FOR i IN EXTRACT (YEAR FROM d_from) .. EXTRACT (YEAR FROM d_to)
7 LOOP
8 PIPE ROW (i);
9 END LOOP;
10
11 RETURN;
12 END;
13 /
Function created.
SQL> SELECT func_year (DATE '2019-01-01', DATE '2021-01-01') FROM DUAL;
FUNC_YEAR(DATE'2019-01-01',DATE'2021-01-01')
----------------------------------------------------------------------------------------------------
T_YEARS('2019', '2020', '2021')
SQL>
Or
SQL> SELECT * FROM TABLE (func_year (DATE '2019-01-01', DATE '2021-01-01'));
COLU
----
2019
2020
2021
SQL>

converting a plsql code into a function

I have this piece of code which I want to convert into a function , and call the function in a select statement by passing vendor_site_id from ap_supplier_sites_all. so that I can get the value of vendor_number i.e segment1 of ap_suppliers . here in this piece of code , I have a login to fetch first 6 digits from the column attribute52 of DFF table gecm_dff_ext .
DECLARE
v_ret_val VARCHAR2(30);
v_sup_gsl VARCHAR2(30);
v_vendor_id NUMBER;
BEGIN
v_vendor_id := '${PO.H_VENDOR_ID}';--> vendor_id column from ap_suppliers
IF <condition> = 'Y'
THEN
BEGIN
SELECT SUBSTR(ATTRIBUTE52,1,6)
INTO v_sup_gsl
FROM gecm_dff_ext
WHERE primary_table ='AP_SUPPLIER_SITES_ALL'
AND primary_key = '${PO.H_VENDOR_SITE_ID}';--> This value should be vendor_site_id from ap_supplier_sites_all table
EXCEPTION
WHEN OTHERS THEN
v_sup_gsl := NULL;
END;
BEGIN
IF v_sup_gsl IS NOT NULL THEN
SELECT segment1
INTO v_ret_val
FROM ap_suppliers
WHERE segment1 = v_sup_gsl;
END IF;
EXCEPTION
WHEN OTHERS THEN
v_ret_val := '';
END;
END IF;
IF v_sup_gsl IS NULL THEN
BEGIN
SELECT SEGMENT1
INTO v_ret_val
FROM ap_suppliers
WHERE vendor_id=v_vendor_id;
EXCEPTION
WHEN OTHERS THEN
v_ret_val := '';
END;
END IF;
:return_value:=v_ret_val;
END;
This is a simplified example: the following SELECT returns department name for a certain department number:
SQL> select dname
2 from dept
3 where deptno = &par_deptno;
Enter value for par_deptno: 10
DNAME
--------------
ACCOUNTING
SQL>
So, how to convert it to a function? By using a proper syntax, declaring a return variable, fetching into it and - returning the result:
SQL> create or replace function f_test (par_deptno in dept.deptno%type)
2 return dept.dname%type
3 is
4 retval dept.dname%type;
5 begin
6 select dname
7 into retval
8 from dept
9 where deptno = par_deptno;
10
11 return retval;
12 exception
13 when no_data_found then
14 return null;
15 end;
16 /
Function created.
SQL> select f_test(10) from dual;
F_TEST(10)
---------------------------------------------------------------------------
ACCOUNTING
SQL> select f_test(999) from dual;
F_TEST(999)
---------------------------------------------------------------------------
SQL>
This is what you should do. It seems that you are returning the v_ret_val, so - your code might look like this:
create or replace function f_test (par_vendor_id po.h_vendor_id%type)
return ap_suppliers.segment1%type
is
v_ret_val ap_suppliers.segment1%type;
begin
if <condition> = 'Y' then
...
end if;
return v_ret_val;
end;

Check String of characters is a valid date or not

I have a table with field sourcefilename which has 5 records. Following are the records.
SN. SOURCEFILENAME
1. 20170215095453_1.Iredell Memorial Hospital Dental Eligibility.xls_INFREPT01.txt
2. Iredell Memorial Hospital Eligibility April 2017.xls_INFREPT01.txt
3. Iredell Memorial Hospital Eligibility March 2017.xls_INFREPT01.txt
4. Iredell Memorial Hospital Eligibility May 2017.xls_INFREPT01.txt
5. Iredell Memorial Hospital October 2016 Dental Eligibility.xls_EligData.txt
I just need to extract first 8 characters and check if its a valid date. If it is a valid date then return TRUE else FALSE.
I tried ISDATE function. Is there are any other alternatives?
SELECT DISTINCT SubStr(sourcefilename,1,8),
CASE WHEN isdate(SubStr(sourcefilename,1,8),'YYYYMMDD') = 1 THEN 'TRUE' ELSE 'FALSE' END FROM ai_4451_1_metl;
Oracle 12.2 provides a new function VALIDATE_CONVERSION. So far I never used it, but I assume it would be like this:
CASE VALIDATE_CONVERSION(SubStr(sourcefilename,1,8) AS DATE, 'YYYYMMDD')
WHEN 1 THEN 'TRUE'
ELSE 'FALSE'
END
If you have Oracle 12.2 you can use the validate_conversion function:
with demo as
( select '20170101' as sourcetest from dual union all
select '20171100' from dual )
select sourcetest
, validate_conversion(sourcetest as date, 'YYYYMMDD') as test_result
from demo;
SOURCETEST TEST_RESULT
----------- -----------
20170101 1
20171100 0
There is no Oracle built_in isdate() or differently named equivalent (in versions before 12cR2). But you can write your own:
create or replace function isdate
( p_date_str in varchar2
, p_date_fmt in varchar2 )
return varchar2
is
return_value varchar2(5);
l_date date;
begin
begin
l_date := to_date(p_date_str, p_date_fmt);
return_value := 'TRUE';
exception
when others then
return_value := 'FALSE';
end;
return return_value;
end isdate;
/
If casting the string to a DATE datatype succeeds it's a valid date, otherwise it isn't.
If your data quality issues are such that your strings have multiple date formats then you can implement this alternate solution.
create or replace function isdate
( p_date_str in varchar2 )
return varchar2
is
return_value varchar2(5) := 'FALSE';
l_date date;
l_date_fmts sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll (
'DD-MON-YYYY'
, 'YYYY-MM-DD'
, 'DD-MM-YY'
-- etc
);
begin
for idx in 1..l_date_fmts.count() loop
begin
l_date := to_date(p_date_str, l_date_fmts)idx) );
return_value := 'TRUE';
exit;
exception
when others then
null;
end;
end loop;
return return_value;
end isdate;
/

oracle - convert many date formats to a single formatted date

I want to bring a string which contains a date to a single format date.
EX:
13-06-2012 to 13-JUN-12
13/06/2012 to 13-JUN-12
13-JUN-2012 to
13-JUN-12
13/jun-2012 to 13-JUN-12
...
I tried to delete all special characters and after that use a function to transform that string into a single format of date. My function return more exceptions, I don't know why...
The function:
CREATE OR REPLACE FUNCTION normalize_date (data_in IN VARCHAR2)
RETURN DATE
IS
tmp_month VARCHAR2 (3);
tmp_day VARCHAR2 (2);
tmp_year VARCHAR2 (4);
TMP_YEAR_NUMBER NUMBER;
result DATE;
BEGIN
tmp_day := SUBSTR (data_in, 1, 2);
tmp_year := SUBSTR (data_in, -4);
--if(REGEXP_LIKE(SUBSTR(data_in,3,2), '[:alpha:]')) then
if(SUBSTR(data_in,3,1) in ('a','j','i','f','m','s','o','n','d','A','J','I','F','M','S','O','N','D')) then
tmp_month := UPPER(SUBSTR (data_in, 3, 3));
else
tmp_month := SUBSTR (data_in, 3, 2);
end if;
DBMS_OUTPUT.put_line (tmp_year);
TMP_YEAR_NUMBER := TO_NUMBER (tmp_year);
IF (tmp_month = 'JAN')
THEN
tmp_month := '01';
END IF;
IF (tmp_month = 'FEB')
THEN
tmp_month := '02';
END IF;
IF (tmp_month = 'MAR')
THEN
tmp_month := '03';
END IF;
IF (tmp_month = 'APR')
THEN
tmp_month := '04';
END IF;
IF (tmp_month = 'MAY')
THEN
tmp_month := '05';
END IF;
IF (tmp_month = 'JUN')
THEN
tmp_month := '06';
END IF;
IF (tmp_month = 'JUL')
THEN
tmp_month := '07';
END IF;
IF (tmp_month = 'AUG')
THEN
tmp_month := '08';
END IF;
IF (tmp_month = 'SEP')
THEN
tmp_month := '09';
END IF;
IF (tmp_month = 'OCT')
THEN
tmp_month := '10';
END IF;
IF (tmp_month = 'NOV')
THEN
tmp_month := '11';
END IF;
IF (tmp_month = 'DEC')
THEN
tmp_month := '12';
END IF;
-- dbms_output.put_line(tmp_day || '~'||tmp_year || '~' ||tmp_month);
IF (LENGTH (tmp_day || tmp_year || tmp_month) <> 8)
THEN
result := TO_DATE ('31122999', 'DDMMYYYY');
RETURN result;
END IF;
-- dbms_output.put_line('before end');
result:=TO_DATE (tmp_day || tmp_month ||tmp_year , 'DDMMYYYY');
-- dbms_output.put_line('date result: '|| result);
RETURN result;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
NULL;
WHEN OTHERS
THEN
result := TO_DATE ('3012299', 'DDMMYYYY');
RETURN result;
RAISE;
END normalize_date;
Usage
SELECT customer_no,
str_data_expirare,
normalize_date (str_data_expirare_trim) AS data_expirare_buletin
FROM (SELECT customer_no,
str_data_expirare,
REGEXP_REPLACE (str_data_expirare, '[^a-zA-Z0-9]+', '')
AS str_data_expirare_trim
FROM (SELECT Q1.set_act_id_1,
Q1.customer_no,
NVL (SUBSTR (set_act_id_1,
INSTR (set_act_id_1,
'+',
1,
5)
+ 1,
LENGTH (set_act_id_1)),
'NULL')
AS str_data_expirare
FROM STAGE_CORE.IFLEX_CUSTOMERS Q1
WHERE Q1.set_act_id_1 IS NOT NULL
)
);
If you have a sound idea of all the possible date formats it might be easier to use brute force:
create or replace function clean_date
( p_date_str in varchar2)
return date
is
l_dt_fmt_nt sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll
('DD-MON-YYYY', 'DD-MON-YY', 'DD-MM-YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD'
, 'DD/MM/YYYY', 'MM/DD/YYYY', 'YYYY/MM/DD', 'DD/MM/YY', 'MM/DD/YY');
return_value date;
begin
for idx in l_dt_fmt_nt.first()..l_dt_fmt_nt.last()
loop
begin
return_value := to_date(p_date_str, l_dt_fmt_nt(idx));
exit;
exception
when others then null;
end;
end loop;
if return_value is null then
raise no_data_found;
end if;
return return_value;
exception
when no_data_found then
raise_application_error(-20000, p_date_str|| ' is unknown date format');
end clean_date;
/
Be aware that modern versions of Oracle are quite forgiving with date conversion. This function handled dates in formats which aren't in the list, with some interesting consequences:
SQL> select clean_date('20160817') from dual;
CLEAN_DAT
---------
17-AUG-16
SQL> select clean_date('160817') from dual;
CLEAN_DAT
---------
16-AUG-17
SQL>
Which demonstrates the limits of automated data cleansing in the face of lax data integrity rules. The wages of sin is corrupted data.
#AlexPoole raises the matter of using the 'RR' format. This element of the date mask was introduced as a Y2K kludge. It's rather depressing that we're still discussing it almost two decades into the new Millennium.
Anyway, the issue is this. If we cast this string '161225' to a date what century does it have? Well, 'yymmdd' will give 2016-12-15. Fair enough, but what about '991225'? How likely is that the date we really want is 2099-12-15? This is where the 'RR' format comes into play. Basically it defaults the century: numbers 00-49 default to 20, 50-99 default to 19. This window was determined by the Y2K issue: in 2000 it was more likely that '98 referred to the recent past than the near future, and similar logic applied to '02. Hence the halfway point of 1950. Note this is a fixed point not a sliding window. As we move further from the year 2000 the less useful that pivot point becomes. Find out more.
Anyway, the key point is that 'RRRR' does not play nicely with other date formats: to_date('501212', 'rrrrmmdd') hurlsora-01843: not a valid month. So, use'RR'and test for it before using'YYYY'`. So my revised function (with some tidying up) looks like this:
create or replace function clean_date
( p_date_str in varchar2)
return date
is
l_dt_fmt_nt sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll
('DD-MM-RR', 'MM-DD-RR', 'RR-MM-DD', 'RR-DD-MM'
, 'DD-MM-YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD', 'YYYY-DD-MM');
return_value date;
begin
for idx in l_dt_fmt_nt.first()..l_dt_fmt_nt.last()
loop
begin
return_value := to_date(p_date_str, l_dt_fmt_nt(idx));
exit;
exception
when others then null;
end;
end loop;
if return_value is null then
raise no_data_found;
end if;
return return_value;
exception
when no_data_found then
raise_application_error(-20000, p_date_str|| ' is unknown date format');
end clean_date;
/
The key point remains: there's a limit to how smart we can make this function when it comes to interpreting dates, so make sure you lead with the best fit. If you think most of your date strings fit day-month-year put that first; you will still get some wrong casts but less that if you lead with year-month-day.
The String-to-Date Conversion Rules allow additional formatting rules (without any other modifiers being applied). (Also see this question) So:
MM also matches MON and MONTH;
MON also matches MONTH (and vice versa);
YY also matches YYYY;
RR also matches RRRR; and
The punctuation is optional.
Which means you can do:
CREATE OR REPLACE FUNCTION parse_Date_String(
in_string VARCHAR2
) RETURN DATE DETERMINISTIC
IS
BEGIN
BEGIN
RETURN TO_DATE( in_string, 'DD-MM-YY' );
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
BEGIN
RETURN TO_DATE( in_string, 'MM-DD-YY' );
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
BEGIN
RETURN TO_DATE( in_string, 'YY-MM-DD' );
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
RETURN NULL;
END;
/
Query:
WITH dates ( value ) AS (
SELECT '010101' FROM DUAL UNION ALL
SELECT '02JAN01' FROM DUAL UNION ALL
SELECT '03JANUARY01' FROM DUAL UNION ALL
SELECT '04012001' FROM DUAL UNION ALL
SELECT '05JAN2001' FROM DUAL UNION ALL
SELECT '06JANUARY2001' FROM DUAL UNION ALL
SELECT 'JAN0701' FROM DUAL UNION ALL
SELECT 'JANUARY0801' FROM DUAL UNION ALL
SELECT 'JAN0901' FROM DUAL UNION ALL
SELECT 'JANUARY1001' FROM DUAL UNION ALL
SELECT '990111' FROM DUAL UNION ALL
SELECT '99JAN12' FROM DUAL UNION ALL
SELECT '99JANUARY13' FROM DUAL UNION ALL
SELECT '19990114' FROM DUAL UNION ALL
SELECT '2001-01-15' FROM DUAL UNION ALL
SELECT '2001JAN16' FROM DUAL UNION ALL
SELECT '2001JANUARY17' FROM DUAL UNION ALL
SELECT '20010118' FROM DUAL
)
SELECT value, parse_Date_String( value ) AS dt
FROM dates;
Output:
VALUE DT
------------- -------------------
010101 2001-01-01 00:00:00
02JAN01 2001-01-02 00:00:00
03JANUARY01 2001-01-03 00:00:00
04012001 2001-01-04 00:00:00
05JAN2001 2001-01-05 00:00:00
06JANUARY2001 2001-01-06 00:00:00
JAN0701 2001-01-07 00:00:00
JANUARY0801 2001-01-08 00:00:00
JAN092001 2001-01-09 00:00:00
JANUARY102001 2001-01-10 00:00:00
990111 2099-01-11 00:00:00
99JAN12 2099-01-12 00:00:00
99JANUARY13 2099-01-13 00:00:00
19990114 1999-01-14 00:00:00
2001-01-15 2001-01-15 00:00:00
2001JAN16 2001-01-16 00:00:00
2001JANUARY17 2001-01-17 00:00:00
20010118 0118-01-20 00:00:00
(Note: the date formats you are using are ambiguous, as the last example demonstrates. You can swap the order the formats are parsed in the function to get different results but if you have 010203 is it 01-FEB-2003, 02-JAN-2003, 03-FEB-2001 or even 01-FEB-0003?)
If you want it in the format DD-MON-YY (but why YY and not YYYY?) then just use:
TO_CHAR( parse_Date_String( value ), 'DD-MON-YY' )

Resources