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

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;
/

Related

Sysdate as char instead of date

I have a query.
i have a config table AB where a row is marked as "sysdate-360"
col1 ||col2
AB || sysdate-360
BC || sysdate -2
When i write a procedure to get date value from the config table AB i used.
v_date varchar(20);
cursor c1 as
select col2 from AB;
then
for ab_date in c1
loop
select ab_date.col2 into v_date from dual;
v_sql := 'delete from any_table where load_date <='||v_date;
execute immediate v_sql ;
commit;
end loop;
The procedure is compiled but when i execute I'm getting below error
ORA-01722: invalid number
ORA-06512: at "procedure", line 46
ORA-06512: at line 1
01722. 00000 - "invalid number"
*Cause:
*Action:
The sysdate -360 is considered as char but not as date since SYSDATE is itself a date right?
Please help.
If you handle only expressions SYSDATE +/- N I'd suggest to modify the config table as follows
ID SYSDATE_OFFSET
-- --------------
AB -360
BC -2
So you have a numeric offset to sysdate which can be queried this way:
select sysdate + (select SYSDATE_OFFSET from config where id = 'AB') s_360
from dual;
S_360
-----------------
25.02.16 21:46:50
So you may open a cursor with the query above.
If you can't change the table - define a view that removes the string sysdate and converts to number!
This looks quite fine to me. But why do you select into v_date? You get a string from the cursor which you can concatenate directly:
for ab_date in c1 loop
v_sql := 'delete from any_table where load_date <=' || ab_date.col2;
execute immediate v_sql ;
commit;
end loop;
At last this is simply the concatanation of two strings 'delete from any_table where load_date <=' and 'sysdate-360' which makes 'delete from any_table where load_date <= sysdate-360' - exactly the SQL string you want.
(That would look even better with a proper column name such as date_expression instead of col2.)
More elaborate explanation: The cursor gets you the string 'sysdate-360'. The query select ab_date.col2 into v_date from dual; is simply v_date := ab_date.col2;. But is v_date a string? If not, you get a conversion error, because 'sysdate-360' is just a string, nothing more. If you expect the DBMS to see that the string contains 'sysdate' which also happens to be the name of a system variable for the current time and then convert this magically, you expect to much.
Try the to_date function
TO_DATE(v_date)

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;

Sqlplus pl/sql Date/Time user input understood as bind variable

I am facing a strange issue.
I have a small pl/sql anonymous block which prompt the user for a date. I want to re-use this date in a query later, but I get an error like "SP2-0552: Bind variable "01" not declared.".
The issue is that ":01" in the time is interpreted as a bind variable. A workaround is to enter the date between quote '2014/04/16 01:01:01' and not directly 2014/04/16 01:01:01.
However, I want to be able to enter my date without the quote.
here is a simple script:
declare
adate VARCHAR2(20);
begin
adate := &adate;
query := 'select to_date(''' || adate ||''', ''YYYY/MM/DD HH24:MI:SS'') from dual';
dbms_output.put_line(query);
end;
Enter value for adate: 2014/04/15 01:01:01
old 4: adate := &adate;
new 4: adate := 2014/04/15 01:01:01;
SP2-0552: Bind variable "01" not declared.
I found the answer.
The variable must be between quote in the script.
declare
adate VARCHAR2(20);
begin
adate := '&adate';
query := 'select to_date(''' || adate ||''', ''YYYY/MM/DD HH24:MI:SS'') from dual';
dbms_output.put_line(query);
end;

Matching system date to select file SQL

I have a list of files in a directory /XX/XX_XX/XX that have the date as YYYYMMDD after the file name
Files20130726.xxx
Files20130727.xxx
Files20130728.xxx
Files20130729.xxx
Files20130730.xxx
Files20130731.xxx
I need to take the current system date and select the file that has the matching date
Example: (system date 7/31/2013 = File20130731.xxx)
I created a procedure that will select the file with the correct system date from the directory
PROCEDURE xxxxxx
uu_f_name VARCHAR2(20) := 'Files.xxx';
uu_infile utl_file.file_type;
BEGIN
CREATE DIRECTORY NEW_DIRECTORY as '/XX/XX_XX/XX';
uu_infile := utl_file.fopen('/XX/XX_XX/XX', to_date(substr(uu_f_name,6, sysdate), 'YYYYMMDD'), 'MM/DD/YYYY', 'r');
I don't really know how to declare the Files.xxx because it actually FilesYYYYMMDD.xxx (so not sure if I can just declare it as 'FilesYYYYMMDD')
I am stuck on how to select the current system date and match it with the correct file. This is what I have but I know that it is not correct but I am lost at how to do this.
to_date(substr(uu_f_name,6, sysdate), 'YYYYMMDD'), 'MM/DD/YYYY', 'r');
Make yourself familiar with:
Format Models.
How to convert strings to dates and other way round with to_char and to_date functions that use format models.
How to concatenate strings with concat function and || operator.
There's plenty of questions here about all of these subjects you can learn from.
Example that should get you started:
JANI#xe> select sysdate from dual;
SYSDATE
-------------------
2013-08-01 07:52:55
JANI#xe> select 'Files.' || to_char(sysdate, 'YYYYMMDD') || '.xxx' as filename from dual;
FILENAME
------------------
Files.20130801.xxx
JANI#xe> !cat so25.sql
declare
v_filename constant varchar2(32767) :=
'Files.' || to_char(sysdate, 'YYYYMMDD') || '.xxx';
begin
dbms_output.put_line('v_filename = ' || v_filename);
end;
/
JANI#xe> #so25.sql
v_filename = Files.20130801.xxx
PL/SQL procedure successfully completed.
JANI#xe>
After that we can come back to your UTL_FILE issues if you have any.

Oracle PL/SQL, How to calculate age from date birth using simple substitution variable and months_between

I am working on a simple PL/SQL block that asks the user their Date Of Birth and calculates their age. I've used the months_between divided by 12 conversion but I am having trouble with the date conversion and date input from the user for the substitution variable. Please ignore the v_birthday_year as that is another part of the code I have to integrate in later.
I'm not sure the format that the user has to type in, ie 05-07-1980, or 06 Mar 1978 that would be acceptable, and how to calculate their age from what they put in.
My desired program is to write a PL/SQL program to accept the user's birthdate in this format DD-MON-YYYY, and calculates the Age in with 1 Decimal place. So I need it calculated out to one decimal place too.
Here is what I have, but I'm not sure what format to type in the DOB at the substitution variable input and the actual calculation with one decimal place. I'm just trying to see where I'm going wrong and how to correct it.
SET SERVEROUTPUT ON
DECLARE
--v_birthday_year NUMBER(4) := &v_birthday_year;
v_dob DATE := &v_dob
v_your_age NUMBER(3, 1);
BEGIN
v_your_age := TRUNC(MONTHS_BETWEEN(SYSDATE, v_dob))/12;
DBMS_OUTPUT.PUT_LINE ('Your age is ' || v_your_age);
END;
/
You may use any of these (pure sql)
SELECT months_between(sysdate, user_birth_date) /12 FROM dual;
or
SELECT floor(months_between(sysdate, user_birth_date) /12) FROM dual;
or
SELECT EXTRACT(YEAR FROM sysdate) - EXTRACT(YEAR FROM user_birth_date) FROM dual
or
SELECT (sysdate - user_birth_date) / 365.242199 FROM dual
Hope this will help
All SQL examples from others and me are probably better thing to use unless you are learning something about PL/SQL. Here's what I came up with:
DECLARE
v_dob DATE:= to_date('&v_dob', 'MM/DD/YYYY'); -- copy this line and you'll be fine
v_your_age NUMBER(3, 1);
BEGIN
v_your_age := TRUNC(MONTHS_BETWEEN(SYSDATE, v_dob))/12;
DBMS_OUTPUT.PUT_LINE ('Your age is ' || v_your_age);
END;
/
I passed 01/01/2010. Got this in output:
Your age is 3.1
Another SQL example:
SELECT empno, ename, hiredate
, TRUNC(MONTHS_BETWEEN(sysdate, hiredate)/12) years_of_service
FROM scott.emp
/
Create or replace function getAge(birthday date) return number is
v_your_age NUMBER(3, 1);``
BEGIN
v_your_age := floor(MONTHS_BETWEEN(SYSDATE, birthday))/12;
return v_your_age;
END;
/
then you call the function
BEGIN
DBMS_OUTPUT.PUT_LINE ('Your age is ' || getAge(to_date('10/10/2015','DD/MM/YYYY')));
end;
/
select dob,sysdate,trunc(months_between(sysdate,dob)/12) as year,
trunc(mod(months_between(sysdate,dob),12)) as month,
trunc(sysdate - add_months(dob,((trunc(months_between(sysdate,dob)/12)*12) + trunc(mod(months_between(sysdate,dob),12))))) as day
from emp;