"ORA-01861: literal does not match format string" error in pl/sql code while inserting a date argument

StackOverflow https://stackoverflow.com/questions/23454212

  •  15-07-2023
  •  | 
  •  

Question

CREATE OR REPLACE PROCEDURE ADD_COMPLEX_SALE_TO_DB(pcustid NUMBER, pprodid NUMBER, pqty NUMBER, pdate VARCHAR2) AS
ERR_INVALID_STATUS EXCEPTION;
ERR_QTY_OUT_RANGE EXCEPTION;
ERR_INVALID_DATE EXCEPTION;
ERR_CUST_NOTFOUND EXCEPTION;
ERR_PROD_NOTFOUND EXCEPTION;
vcustid NUMBER(10);
vstatus VARCHAR2(5);
vamt NUMBER(10);
vSellPrice NUMBER(10);
PRAGMA EXCEPTION_INIT(ERR_PROD_NOTFOUND, 100);

BEGIN

IF pqty < 1 OR pqty > 999 THEN
RAISE ERR_QTY_OUT_RANGE;
END IF;

vStatus := 'OK';
IF vStatus = 'OK' THEN
UPDATE customer SET status = vStatus WHERE custid = pcustid;
IF SQL%NOTFOUND THEN
RAISE ERR_CUST_NOTFOUND;
END IF;
ELSE
RAISE ERR_INVALID_STATUS;
END IF;

IF pdate = TO_DATE(pdate, 'YYYYMMDD') THEN
INSERT INTO sale(saleid, custid, prodid, qty, price, saledate) VALUES(SALE_SEQ.nextVal, pcustid, pprodid, pqty, vamt, TO_DATE(pdate));
ELSE
RAISE ERR_INVALID_DATE;
END IF;

SELECT selling_price INTO vSellPrice FROM product WHERE prodid = pprodid;
IF SQL%NOTFOUND THEN
RAISE ERR_PROD_NOTFOUND;
END IF;
vamt := pqty * vSellPrice;
UPD_CUST_SALESYTD_IN_DB(pcustid, vamt);
UPD_PROD_SALESYTD_IN_DB(pprodid, vamt);    

EXCEPTION
WHEN ERR_QTY_OUT_RANGE THEN
RAISE_APPLICATION_ERROR(-20091, 'Sale Quantity outside valid range');
WHEN ERR_INVALID_STATUS THEN
RAISE_APPLICATION_ERROR(-20092, 'Customer status not OK');
WHEN ERR_INVALID_DATE THEN
RAISE_APPLICATION_ERROR(-20093, 'Date not valid');
WHEN ERR_CUST_NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20094, 'Customer ID not found');
WHEN ERR_PROD_NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20095, 'Product ID not found');
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20000, sqlerrm);
END;

I'm getting "ORA-01861: literal does not match format string" error when executing this code. Where am i getting wrong in this code? I have attached question snippet as well with it. The 'saledate' variable in actual table where value is being inserted is of datatype date but i'm supposed to enter date through procedure as varchar2 dataype. I converted date with to_date() function but still got same error

Was it helpful?

Solution

you are trying to handle invalid date format in the wrong way

try using a separate try catch block around your pdate variable

declare
   invalid_date varchar2(10) := '201401';
   d date;
begin
   begin
           d := to_date(invalid_date,'yyyymmdd');
   exception when others then
           dbms_output.put_line('Handling invalid date');
   end;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top