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

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;

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.

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;

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.