0

Hi I have the following function created in Oracle. i will have to pass date-1 and date-2 parameters into the function and the function should return the another date to me .

please see the code below.

create or replace function GETD(p_d1   in date, 
                                p_d2   in date ) return DATE 
   as 
       l_result    DATE; 
   begin 
    SELECT EDIT_Date into l_result FROM qa.employees  WHERE qa.employee_join_date BETWEEN TO_DATE(p_d1, 'MM/DD/YYYY') AND TO_DATE(p_d2, 'MM/DD/YYYY') AND ROWNUM <= 1
    ;
       return l_result; 
  end; 

i execute the function as below

SELECT GETD('27-JUN-12','28-JUN-12') FROM DUAL

the function get compiled and while im passing the parameters to execute the function i get the following error "Not a Valid Month". Could some one please tell me where im going wrong

thanks Justin

1 Answer 1

1

First, you should not call TO_DATE on a date variable. If you do that, you force Oracle to first convert the date to a string using the session's NLS_DATE_FORMAT and then convert the string back to a date using the specified format mask. If your NLS_DATE_FORMAT happens not to match the specified format mask (and, since the NLS_DATE_FORMAT is controlled by the client, some users and sessions will inevitably have a different date format), you'll get an error.

Assuming your intention was merely to ignore any time component, you should be using the trunc function instead.

create or replace function GETD(p_d1   in date, 
                                p_d2   in date ) 
  return DATE 
as 
  l_result    DATE; 
begin 
  SELECT EDIT_Date 
    into l_result 
    FROM qa.employees  
   WHERE qa.employee_join_date BETWEEN trunc(p_d1) AND trunc(p_d2) 
     AND ROWNUM <= 1;

  return l_result; 
end; 

The presence of a rownum <= 1 condition seems a bit odd-- it seems unlikely that you really want to fetch an arbitrary row from the table that matches the employee_join_date criteria. Not knowing the requirements, it seems likely that you want to do something deterministic that fetches the row with the minimum (or maximum) edit_date.

Second, when you call the function, you should pass in DATE parameters rather than passing in strings and letting Oracle implicitly convert the strings to dates using the session's NLS_DATE_FORMAT. If you use date literals

SELECT GETD(date '2012-06-27', date '2012-06-28') 
  FROM DUAL

or convert the strings to dates explicitly using a TO_DATE

SELECT GETD(to_date('27-JUN-12', 'DD-MON-RR'), to_date('28-JUN-12', 'DD-MON-RR')) 
  FROM DUAL

then your call will work regardless of the client's NLS_DATE_FORMAT.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.