Oracle Date Format with input Parametres - PLSQL - sql

I'm getting an error as follows:
ORA-01858 - a non-numeric character was found where a numeric character was expected.
Although it isn't really accurate, I believe it's related to the date formatting in the following lines.
ELSIF par_report_eff_date_start IS NOT NULL AND par_report_eff_date_start = to_date(par_report_eff_date_start, 'fxdd-mm-yyyy')
and
ELSIF par_report_eff_date_end IS NOT NULL AND par_report_eff_date_end = to_date( par_report_eff_date_end ,'fxDD-MM-YYYY')
I'm trying to get the parameters to render date in the format of 'dd/mm/yyyy' as it is passed in, but i'm not sure how to get around this.
I have looked, but have limited web access at work, so I can't use the regular sites.
procedure collect_mon_comm_bal_data_part (
par_report_eff_date_start DATE DEFAULT NULL, --dd/mm/yyyy;
par_report_eff_date_end DATE DEFAULT NULL) --dd/mm/yyyy;
is
v_report_eff_date_start DATE;
v_report_eff_date_end DATE;
BEGIN
IF par_report_eff_date_start IS NULL
THEN
-- Oracle job runs at the beginning of each month
select trunc(trunc(sysdate,'Mon')-1,'Mon')
into v_report_eff_date_start
from dual; -- Start of month Var
ELSIF par_report_eff_date_start IS NOT NULL AND par_report_eff_date_start = to_char(par_report_eff_date_start, 'fxdd/mm/yyyy')
THEN
v_report_eff_date_start := par_report_eff_date_start;
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_start || 'Is The Start Date');
ELSE
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_start || 'Is is the wrong format, needs tp be in dd/mm/yyyy');
GOTO the_end;
END IF;
IF par_report_eff_date_end IS NULL
THEN
-- Oracle job runs at the beginning of each month
select trunc(sysdate,'MM')-1
into v_report_eff_date_end
from dual; -- Start of month Var
ELSIF par_report_eff_date_end IS NOT NULL AND par_report_eff_date_end = to_char(par_report_eff_date_end, 'fxdd/mm/yyyy')
THEN
v_report_eff_date_end := par_report_eff_date_end;
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_end || 'Is The Start Date');
ELSE
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_end || 'Is is the wrong format, needs tp be in dd/mm/yyyy');
GOTO the_end;
END IF;
END;

You don't want to convert a date to a date. You want to convert it to a character string. So try:
to_char(par_report_eff_date_start, 'fxdd-mm-yyyy')
I'm not sure what the rest of the logic is supposed to be doing. But, you use to_date() to convert a value to a date and to_char() to convert a value to a string.

I notice that you have parameter par_report_eff_date_start, and a variable v_report_eff_date_start. You probably want to compare those in the following line:
ELSIF par_report_eff_date_start IS NOT NULL AND par_report_eff_date_start = to_char(par_report_eff_date_start, 'fxdd/mm/yyyy')
But now you are comparing the date parameter with a text value derived from the parameter value. I don't think that's what you want.
A date is just a date, and you only have to think about format masks when converting it to another data type (like VARCHAR2).
So why not use:
ELSIF par_report_eff_date_start IS NOT NULL AND trunc(par_report_eff_date_start) = trunc(sysdate, 'Mon')
I've added trunc() to the parameter value, and because you want the first day of the month (I guess!!), trunc(sysdate, 'Mon') will do just fine.

Thank You Gordon, I think I've found a way around it.
procedure collect_mon_comm_bal_data_part (
par_report_eff_date_start VARCHAR2 DEFAULT NULL, --dd/mm/yyyy;
par_report_eff_date_end VARCHAR2 DEFAULT NULL) --dd/mm/yyyy; is
v_report_eff_date_start DATE; v_report_eff_date_end DATE;
BEGIN
IF par_report_eff_date_start IS NULL
THEN
-- Oracle job runs at the beginning of each month
select trunc(trunc(sysdate,'Mon')-1,'Mon')
into v_report_eff_date_start
from dual; -- Start of month Var
ELSIF par_report_eff_date_start IS NOT NULL AND to_date(par_report_eff_date_start, 'dd/mm/yyyy') = to_date(par_report_eff_date_start,'fxdd/mm/yyyy')
THEN
v_report_eff_date_start := to_date(par_report_eff_date_start, 'dd/mm/yyyy');
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_start || 'Is The Start Date');
ELSE
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_start || 'Is is the wrong format, needs tp be in dd/mm/yyyy');
GOTO the_end; END IF;
IF par_report_eff_date_end IS NULL
THEN
-- Oracle job runs at the beginning of each month
select trunc(sysdate,'MM')-1
into v_report_eff_date_end
from dual; -- Start of month Var
ELSIF par_report_eff_date_end IS NOT NULL AND to_date(par_report_eff_date_end, 'dd/mm/yyyy') = to_date(par_report_eff_date_end,'fxdd/mm/yyyy')
THEN
v_report_eff_date_end := to_date(par_report_eff_date_end, 'dd/mm/yyyy');
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_end || 'Is The Start Date');
ELSE
DBMS_OUTPUT.PUT_LINE(par_report_eff_date_end || 'Is is the wrong format, needs tp be in dd/mm/yyyy');
GOTO the_end; END IF;
So I want it to default to a monthly run, for the previous month if the parameters are null. And I want it to run for selected dates, should they be put in manually at execution, this way I can run it for a year period to build up a proper sample of data, that will be updated as it changes going forward.
I have tried to pass in bogus dates, and null dates and they hit the exception or run for a month of data as expected, so this works for me.
Thanks again guys, I really the help!

Related

PL/SQL Invalid object identifier in creating procedure with date field parameter

Im fairly new pl/sql and im trying to create procedure that can take a date parameter from input, find and update the matching join date row(s) from student table I am working on but i cant seem to get a valid date and i'm not sure i properly configured my procedure from input your help would be appreciated, this is my code currently.
CREATE OR REPLACE PROCEDURE dateChanger (p_join_date IN DATE)
IS p_date DATE;
p_month VARCHAR2(3);
p_year VARCHAR2(4);
p_change VARCHAR2(11);
v_month VARCHAR2(3);
BEGIN
p_date := to_date(p_join_date, 'dd-mon-yyyy');
p_month := Extract(MONTH FROM p_date);
p_year := Extract(YEAR FROM p_date);
v_month := to_char(Extract(MONTH FROM student.join_date%TYPE), 'MON');
--expected result 01-(Month from p_date)-(Year from p_date) eg. 01-JUL-2021
p_change := '01-'+to_char(p_month, 'MON')+'-'+to_char(p_year, 'YYYY');-- date put back together
UPDATE Week03.t_student SET join_date = to_date(p_change, 'dd-mon-yyyy')
WHERE v_month = p_month; -- table updated where months match
RETURN(p_date || '-----' || p_change);
END;
/
ACCEPT jDate Date PROMPT 'Please Enter a valid date as dd-MON-YYYY eg. 13-JUL-2021';
DECLARE
dc VARCHAR2(11);
l_date student.join_date%type := &jDate; -- input from user saved to date type variable
BEGIN
dc := DATECHANGER(l_date);
SELECT DATECHANGER(l_date) INTO dc from dual;
END;
/
When i enter the date as 'dd-mon-yyy' or 'yyyy-mon-dd' and many other variations i get a pls 00905 & 00201 error any help would be appreciated. it seems the date input refuses all the variations i've tried.
From documentation:
DATE
Makes reply a valid DATE format. If the reply is not a valid DATE
format, ACCEPT gives an error message and prompts again. The datatype
is CHAR.
That means in this case result of accept of data is char format.
You should change you code a bit.
in announmous block
l_date student.join_date%type := &jDate; => l_date varchar2(100) := '&jDate'
and in procedure
(p_join_date IN DATE) => (p_join_date in varchar2)
Yea so for future references to anyone who may need to complete a similar task to mine here is how i solved my problem thanks a bit to #Arkadiusz Ɓukasiewicz
CREATE OR REPLACE PROCEDURE dateChanger (p_join_date IN DATE)
BEGIN
UPDATE Week03.t_student SET join_date = trunc(join_date, 'MM');
END;
/
SELECT * FROM student;
BEGIN
dateChanger(to_date('2018-09-01', 'yyyy-mm-dd'));
END;
/

How to replace Invalid Date Part (Day / Month) to default 01 if Year is valid

Need Oracle SQL or stored procedure to convert invalid day or month in the date field to 01 if Year is a valid year. The input is in varchar format.
For example, if input value is 20132016 (MMDDYYYY), the Year is a valid value 2016, now I have to check Day and Month.
In the example above, Day is also valid as it's 13, but the month is invalid with a value of 20. So I have to convert month to 01 (default). So the output expected is 01132016.
I need this in my project to to predict someone age, So instead of inserting Null for invalid Date of Birth, I want to retain part of the date value importantly the Year.
I have a function to return valid date but this function does not return the expected result I am looking for.
CREATE OR REPLACE FUNCTION FUNC_CHK_DATE (P_INPUT IN VARCHAR2)
Return Date
Is
v_date DATE := NULL;
BEGIN
V_DATE := TO_DATE( P_INPUT, 'YYYY/MM/DD');
RETURN V_DATE;
EXCEPTION
WHEN OTHERS THEN
RETURN null;
END FUNC_CHK_DATE;
Your first mistake is here:
V_DATE := TO_DATE( P_INPUT, 'YYYY/MM/DD');
You say the expected format is 'MMDDYYYY' (e.g. '20132016'). So why are you trying to convert a string formatted 'YYYY/MM/DD'?
Then, when conversion fails, you are not even trying to detect the erroneous part and repair it, but simply return null. So how can this possibly return the desired date?
Let's start with an agorithm:
Check whether the input string is 8 digits exactly. If not, return null.
Convert to date. If that works, return the date.
Otherwise we'll check the year. Is it zero (which is not allowed in Oracle), we make it 0001.
Convert to date again. If that works, return the date.
Otherwise we'll check the month. Is it zero or greater than 12, we make it 01.
Convert to date again. If that works, return the date.
Otherwise the day is incorrect for the month and year, so we make it 01.
Convert to date again and return the date.
I'm using a loop for convenience here:
CREATE OR REPLACE FUNCTION func_chk_date (p_input IN VARCHAR2)
RETURN DATE
IS
v_date DATE;
v_datestring CHAR(8);
BEGIN
IF NOT REGEXP_LIKE(p_input, '^[[:digit:]]{8}$') THEN
RETURN NULL;
END IF;
v_datestring := p_input;
LOOP -- until conversion okay
BEGIN
v_date := TO_DATE(v_datestring, 'MMDDYYYY');
EXIT; -- conversion okay
EXCEPTION WHEN OTHERS THEN
IF SUBSTR(v_datestring, 5, 4) = '0000' THEN
v_datestring := SUBSTR(v_datestring, 1, 4) || '0001';
ELSIF TO_NUMBER(SUBSTR(v_datestring, 3, 2)) NOT BETWEEN 1 AND 12 THEN
v_datestring := SUBSTR(v_datestring, 1, 2) || '01' || SUBSTR(v_datestring, 5, 4);
ELSE
v_datestring := '01' || SUBSTR(v_datestring, 3, 6);
END IF;
END;
END LOOP;
RETURN V_DATE;
END FUNC_CHK_DATE;
Nesting your tests is one way:
CREATE OR REPLACE FUNCTION func_chk_date (p_input IN VARCHAR2)
RETURN DATE
IS
v_date DATE := NULL;
BEGIN
v_date := TO_DATE (p_input, 'YYYY/MM/DD');
RETURN v_date;
EXCEPTION
WHEN OTHERS
THEN
BEGIN
v_date := TO_DATE (SUBSTR (p_input, 1, 4), 'YYYY');
RETURN v_date;
EXCEPTION
WHEN OTHERS
THEN
RETURN NULL;
END;
END func_chk_date;
You create a function that traps the date errors that you've want to attempt correcting. The following is just one way.
create or replace function func_chk_date (date_string_in varchar2
,date_format_in varchar2 default 'mmddyyyy'
)
return date
is
bad_mon_e exception;
PRAGMA EXCEPTION_INIT(bad_mon_e, -01843);
bad_day_e exception;
PRAGMA EXCEPTION_INIT(bad_day_e, -01839);
bad_mon_day_e exception;
PRAGMA EXCEPTION_INIT(bad_mon_day_e, -01847);
date_value_l date;
function fix_dd
return varchar2
is
begin
return substr(date_string_in,1,2) || '01' || substr(date_string_in,5);
end fix_dd;
function fix_mm
return varchar2
is
begin
return '01' || substr(date_string_in,3);
end fix_mm;
begin
begin
date_value_l:= to_date( date_string_in, date_format_in);
exception
when bad_mon_e then
date_value_l:= func_chk_date (date_string_in => fix_mm
,date_format_in => date_format_in
);
when bad_day_e
or bad_mon_day_e then
date_value_l:=func_chk_date (date_string_in => fix_dd
,date_format_in => date_format_in
);
when others then
null; -- << Actually a very bad idea at least log the error >>
end ;
return date_value_l;
exception
when others then
dbms_output.put_line('Other Error:'|| sqlerrm);
end func_chk_date;
/
Some test data:
begin
dbms_output.put_line ('05052017 returned ' || func_chk_date('05052017'));
dbms_output.put_line ('02292017 returned ' || func_chk_date('02292017'));
dbms_output.put_line ('02292016 returned ' || func_chk_date('02292016'));
dbms_output.put_line ('13292016 returned ' || func_chk_date('13292016'));
dbms_output.put_line ('20402040 returned ' || func_chk_date('20402040'));
dbms_output.put_line ('0505yyyy returned ' || func_chk_date('0505yyyy'));
end ;
The function works as is but is limited to the date format "mmddyyyy". If you want a different format you'll need to modify the fix-mm and/or the fix_dd functions. Also this is a recursive routine so you'll need to guarantee there is a exit path.

How to validate YYYYMMDD date given as parameter PL/SQL

I have a SP called ADD_COMPLEX_SALE. It gets 4 parameters : custid, prod id, qty and date(varchar2).
I need to validate the date and check that it is in the right format. It is being sent to the procedure as YYYYMMDD.
This is what I have so far:
IF (LENGTH(pdate) != 8) THEN
raise_application_error (-20093,' Date not valid');
ELSIF (LENGTH(pdate) = 8)THEN
vDATE := CONVERT(VARCHAR(10), pdate(), 111) AS [YYYY/MM/DD];
END IF;
IF (pdate != 'YYYY/MM/DD') THEN
raise_application_error (-20093,' Date not valid');
END IF;
Basically the idea is too convert it to a 'real' date format so that I can know for sure it is in the proper format. Except I get this error.
Still very new pl/sql so any help will be appreciated.
Error(42,49): PLS-00103: Encountered the symbol "AS" when expecting one of the following: . ( * % & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset member submultiset
UPDATE:
Changed code to the following :
vDATE := TO_DATE(pdate, 'yyyymmdd');
IF (pdate != vDATE) THEN
raise_application_error (-20093,' Date not valid');
END IF;
IF (LENGTH(vDATE) != 8) THEN
raise_application_error (-20093,' Date not valid');
END IF;
Now getting this error:
ORA-20000: Another error occured ORA-01861: literal does not match format string
EDIT: Last update error was due to Parameter being varchar2 and me forgetting to INSERT vDATE instead of pdate after the conversion was done.
convert(varchar(10), pdate(), 111) appears to be an attempt to use the SQL Server convert function. That's not going to work in Oracle.
I'd just do something like
DECLARE
l_dt date;
BEGIN
l_dt := to_date( pdate, 'yyyymmdd' );
EXCEPTION
WHEN others
THEN
raise_application_error( -20001, pdate || ' is not a date in the format YYYYMMDD' );
END;
Of course, if you want to do multiple checks so that you can throw a different exception if the length is incorrect or add some checks to ensure that the date is reasonable (i.e. must be within the last 100 years or no more than 100 years in the future, etc.) you could do that after the to_date conversion.
CREATE PROCEDURE DATECHECK(pdate VARCHAR2) AS
err_date EXCEPTION;
vdate DATE;
BEGIN
BEGIN
vdate := to_date(pdate,'yyyymmdd');
EXCEPTION
WHEN OTHERS THEN
RAISE err_date;
END;
EXCEPTION
WHEN err_date THEN
raise_application_error(-20090, 'DATE ERROR');
END;

Issue when comparing result of to_char(myDate, 'DAY') to a string

I have been trying to find what the issue might be but I am just out of luck and don't understand this problem at all.I have the following code:
CREATE OR REPLACE FUNCTION ckeckDay(dateC in date)
RETURN VARCHAR
IS
day VARCHAR(15);
checkFriday VARCHAR(1);
BEGIN
checkFriday := 'N';
day := to_char(dateC, 'DAY');
IF day = 'FRIDAY' THEN
checkFriday := 'Y';
END IF;
RETURN day;
END;
/
the dateC is set to Friday (even tested it by returning day instead of the day variable and it returns Friday.) However the IF statement never evaluates to true even though the day variable is indeed Friday.Any ideas how to go around this issue.Thanks
If you want to be really robust about this then you ought to force the NLS setting to English and apply the "fill mode" format model FM for trimming leading and trailing spaces.
If To_Char(DateC,'fmDAY', 'nls_date_language=english') = 'FRIDAY'
Then ...
It is because day variable contains a blank padded value. Use trim function to get rid of leading and trailing spaces:
IF trim(day) = 'FRIDAY' THEN
checkFriday := 'Y';
END IF;
And please use VARCHAR2 datatype for string variables. Do not use VARCHAR.

Oracle/SQL: invalid number format model when concatenating a date and a time into a single date value

I am trying to create a trigger in Oracle that compares two dates and then deletes records if the difference of the two dates falls below a certain value. I have a full date value with the format 'DD-MON-YYYY HH24MI' and then for the second date value, I want to concatenate a 'DD-MON-YYYY' value with a 'HH24MI' value.
The problem I am getting is that when I try to concat the date and time value together using to_char, and then using to_date on that returned value, it gives me a ORA-01481 invalid number format error. The relevant lines from the trigger itself are below. If anyone can help me out with this, it would be greatly appreciated!
CREATE OR REPLACE TRIGGER dateTrig
...
DECLARE
day date;
ftime date;
CURSOR c_table1 IS SELECT ...;
BEGIN
FOR entry IN c_table1 LOOP
day := to_date(entry.fdate);
ftime := to_date(to_char(day, 'DD-MON-YYYY') || ' ' || to_char(entry.dtime, 'HH24MI'), 'DD-MON-YYYY HH24MI'); -- this is the line that is causing the error
dbms_output.put_line(day || ', ' || ftime);
END LOOP;
END;
/
Since DTIME is not a date type, you cannot use TO_CHAR with a date format. If it's zero padded to a length of 4 characters, you can simplify it like this:
ftime := to_date(to_char(day, 'DD-MON-YYYY') || ' ' || entry.dtime, 'DD-MON-YYYY HH24MI');
I think your best to avoid using to_char's if you can and try to stick with functions that return values in their native date formats, this way you may also not need to run a to_date command on your string, you may have some success with the following or a close relation to it:
ftime := Trunc(Sysdate) || ' ' || Extract(Hour From entry.dtime) || ':' Extract(Minute From entry.dtime)
Best of luck