Oracle passing a variable to a function - sql

I have some SQL code, which uses a hard coded date. My goal is to remove the hard coded dates and replace them with variables to make the code generic.
My test CASE is the following;
CREATE OR REPLACE FUNCTION IsDate( p_str IN VARCHAR2, p_format IN VARCHAR2 ) RETURN NUMBER AS
V_date DATE;
BEGIN
V_Date := TO_DATE( p_str, p_format );
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
This works fine
select IsDate(DATE '2021-07-31','YYYY-MM-DD') from dual;
This causes an error (see below). Can someone please explain the issue and how can it be fixed.
I'm testing on live SQL. Thanks in advance to all who answer.
exec :my_date := DATE '2021-07-31';
select IsDate( DATE my_date,'YYYY-MM-DD') from dual;
i am getting below error
ORA-01008: not all variables bound ORA-06512: at "SYS.DBMS_SQL", line 1721
ORA-00936: missing expression

There a special function VALIDATE_CONVERSION since 12.2 that does exactly what you want to achieve:
VALIDATE_CONVERSION
Example:
SQL> select VALIDATE_CONVERSION('01-01-2000' as date,'dd-mm-yyyy') chk1 from dual;
CHK1
----------
1
SQL> select VALIDATE_CONVERSION('01-01-2000' as date,'yyyy-mm-dd') chk2 from dual;
CHK2
----------
0
Also livesql.oracle.com doesn't support exec command which is an SQL*Plus command. So if you want to test your functions with bind variables, you can use simple PL/SQL Variables:
declare
string_date varchar2(100);
FUNCTION IsDate( p_str IN VARCHAR2, p_format IN VARCHAR2 ) RETURN NUMBER AS
V_date DATE;
BEGIN
V_Date := TO_DATE( p_str, p_format );
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END;
begin
string_date:='31-12-2000';
dbms_output.put_line(IsDate(string_date,'dd-mm-yyyy'));
end;
/

The DATE keyword expects a literal, you cannot use a string variable.
Regarding your function:
FUNCTION IsDate( p_str IN VARCHAR2, p_format IN VARCHAR2 ) RETURN NUMBER
It expects two VARCHAR2, i.e. string values. However when you run IsDate(DATE '2021-07-31','YYYY-MM-DD') the you pass a DATE value into the function, not a string.
Checking the format of a DATE value is pointless, because a DATE values itself has no format, it is stored as an internal binary value. Never use TO_DATE on a value which is already a DATE. Function TO_DATE expects a string which shall be converted to a DATE.
What is displayed when you select a DATE is defined (by default) with your current user session NLS_DATE_FORMAT setting. You can change the default output format for example with ALTER SESSION SET NLS_DATE_FORMAT = 'DD.MM.YYYY'; or you set it explicitly by using the TO_CHAR() function.
When you call your function IsDate(DATE '2021-07-31','YYYY-MM-DD') then Oracle makes an implicit cast to a string. i.e. it runs
V_Date := TO_DATE( TO_CHAR(p_str, SYS_CONTEXT('USERENV', 'NLS_DATE_FORMAT')), p_format );
When you pass a DATE value, then your function actually acts like this:
CREATE OR REPLACE FUNCTION IsDate( p_str IN VARCHAR2, p_format IN VARCHAR2 ) RETURN NUMBER AS
ret NUMBER;
BEGIN
SELECT COUNT(*)
INTO ret
FROM NLS_SESSION_PARAMETERS
WHERE PARAMETER = 'NLS_DATE_FORMAT'
AND VALUE = p_format;
RETURN ret;
-- p_str is ignored completely
END;
Note, in Oracle 18 the TO_DATE function provides the DEFAULT ... ON CONVERSION ERROR clause, so it may be an overkill to write the extra function.

Related

PLS-00382: expression is of wrong type. PL/SQL: Statement ignored

I tried executing a simple package with function overloading. Below is the package code.
--package specification:
create or replace package over_load as
FUNCTION print_it(v_date date) return date;
FUNCTION print_it(v_name varchar2) return number;
end over_load;
--package body:
create or replace package body over_load as
FUNCTION print_it(v_date date) return date is --function accepting and returning date
begin
dbms_output.put_line('the date is ' || v_date);
return v_date;
end print_it;
FUNCTION print_it(v_name varchar2) return number is /*function accepting string and returning number*/
v_eno employees.employee_id%type;
begin
select employee_id into v_eno from employees where first_name = v_name;
return v_eno;
end print_it;
end over_load;
I tried executing the first function in the package using the below anonymous block.
declare
sample_date date;
begin
sample_date := over_load.print_it('14-07-2017');
dbms_output.put_line(sample_date);
end;
I tried passing date as the argument to the first function, but it throws the wrong argument type error. Any idea on why?
If the procedure (or a function) expects DATE datatype, then don't pass string to it. Because, '14-07-2017' is a string.
SQL> set serveroutput on
SQL>
SQL> declare
2 sample_date date;
3 begin
4 --sample_date := over_load.print_it('14-07-2017');
5 sample_date := over_load.print_it(date '2017-07-14');
6 dbms_output.put_line(sample_date);
7 end;
8 /
the date is 14.07.17
14.07.17
PL/SQL procedure successfully completed.
SQL>
In line #5, I passed a date literal. It could have also been to_date('14-07-2017', 'dd-mm-yyyy').
Oracle - if it can - implicitly converts what you pass to datatype it expects, but it doesn't always succeed; that depends on NLS settings.
To be sure that it'll ALWAYS work, take control over it and use appropriate datatypes.

Creating a user defined function in oracle SQL called lastnamefirst

I am using oracle SQL developper.
I am trying to create a function that will accept two parameters (first and last name) and return them as one variable, with the last name showing up first. Here is my function.
CREATE OR REPLACE FUNCTION LASTNAMEFIRST
(
varFirstName IN VARCHAR2,
varLastName IN VARCHAR2
)
RETURN VARCHAR2 AS
BEGIN
DECLARE varFullName VARCHAR2;
DEFINE varFullName := CONCAT(varLastName,' ' ,varFirstName);
RETURN varFullName;
END LASTNAMEFIRST;
I am receiving an error on the semicolon at 'end lastnamefirst' "syntax error"
I keep trying to change small things and that same error just shows up in different places whenever I change things. What am I doing wrong?
Wrong syntax. Should be
SQL> create or replace function lastnamefirst
2 (varfirstname in varchar2,
3 varlastname in varchar2)
4 return varchar2
5 as
6 begin
7 return varlastname||' '||varfirstname;
8 end;
9 /
Function created.
SQL> select lastnamefirst('Little', 'Foot') result from dual;
RESULT
------------------------------
Foot Little
SQL>
What's wrong with your code?
you don't DECLARE within the body; if you do, there's no DECLARE keyword at all, and datatype requires length (such as VARCHAR2(30))
CONCAT accepts only two arguments; use a concatenation operator, double pipe || instead
there's no DEFINE in PL/SQL
I would expect the Oracle syntax to look more like:
CREATE OR REPLACE FUNCTION LASTNAMEFIRST (
in_FirstName IN VARCHAR2,
in_LastName IN VARCHAR2
)
RETURN VARCHAR2 AS
v_FullName varchar2(4000);
BEGIN
v_FullName := in_LastName || ' ' || in_FirstName;
RETURN v_FullName;
END; -- LASTNAMEFIRST;
This can of course be simplified (say by not using a local variable), but it follows the logic of your code.
Using DECLARE where you have is essentially starting a new code block, which is leading to the error you see. In your code, the DECLAREisn't necessary if you move the variable declaration prior to the BEGIN. DEFINE is also invalid. Something like this should work:
CREATE OR REPLACE FUNCTION LASTNAMEFIRST
(
varFirstName IN VARCHAR2,
varLastName IN VARCHAR2
)
RETURN VARCHAR2 AS
varFullName VARCHAR2(100);
BEGIN
varFullName := varLastName || ' ' || varFirstName;
RETURN varFullName;
END LASTNAMEFIRST;
This could be simplified further by removing the variable declaration completely:
CREATE OR REPLACE FUNCTION LASTNAMEFIRST
(
varFirstName IN VARCHAR2,
varLastName IN VARCHAR2
)
RETURN VARCHAR2 AS
BEGIN
RETURN varLastName || ' ' || varFirstName;
END LASTNAMEFIRST;

Ways of handling unknown data type in oracle

I have a statement that executes a sql like this:
execute immediate cursor_rule.rule_sql into rule_result ;
my problem is that the output of rule_sql can be anything from null, to boolean to a number.
How do I define rule_result in a situation like this?
You can use:
DECLARE
rule_result VARCHAR2(4000);
BEGIN
EXECUTE IMMEDIATE :your_sql INTO rule_result;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL; -- Handle what should happen when the SQL returns zero rows.
WHEN TOO_MANY_ROWS THEN
NULL; -- Handle what should happen when the SQL returns two or more rows.
END;
/
If the result of your sql statement is a:
String data type then it gets stored in the rule_result as is.
numeric data type then Oracle will implicitly call TO_CHAR on it to convert it to a VARCHAR2 value exactly long enough to hold its significant digits.
DATE data type then Oracle will implicitly call TO_CHAR( date_value, NLS_DATE_FORMAT ) using the NLS_DATE_FORMAT session parameter as the format model to convert it to a string.
TIMESTAMP data type then Oracle will implicitly call TO_CHAR( timestamp_value, NLS_TIMESTAMP_FORMAT ) using the NLS_TIMESTAMP_FORMAT session parameter as the format model to convert it to a string.
You can parse the SQL statement using DBMS_SQL to discover the column data type. For example:
declare
l_cursor_id pls_integer := dbms_sql.open_cursor;
l_pointless_count pls_integer;
l_desc_cols dbms_sql.desc_tab;
l_sql long := 'select dummy as teststring, 123 as testnum, sysdate as testdate from dual';
begin
dbms_sql.parse(l_cursor_id, l_sql, dbms_sql.native);
dbms_sql.describe_columns(l_cursor_id, l_pointless_count, l_desc_cols);
for i in 1..l_desc_cols.count loop
dbms_output.put_line
( rpad(l_desc_cols(i).col_name,31) || lpad(l_desc_cols(i).col_type,4) );
end loop;
dbms_sql.close_cursor(l_cursor_id);
end;
Output:
TESTSTRING 1
TESTNUM 2
TESTDATE 12
Type codes are defined in DBMS_TYPES and the documentation (which as I discovered last week do not necessarily agree).

local function inside PL/SQL script

I'm trying to execute this code in Oracle 10 SQL Developer:
FUNCTION is_valid_date (p_val in VARCHAR2, p_format IN VARCHAR2 )
RETURN numeric IS
l_date VARCHAR2(100);
BEGIN
l_date := TO_date( p_val, p_format );
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END is_valid_date;
BEGIN
DBMS_OUTPUT.PUT_LINE(is_valid_date('20120101', 'YYYYMMDD' ));
END;
but I get a generic error without any specific Oracle code, as if it is a syntax problem.
I need to check if a date is valid and, as there is no Oracle built in function for that, I have defined it inside my script (I don't want it to be global or stored somewhere).
Edit:
I have found a solution on an oracle forum using oracle regexp, instead of a function. My script is:
BEGIN
select * from mytable where not REGEXP_LIKE(mydatefield, '(((0[1-9]|[12]\d|3[01])\.(0[13578]|1[02])\.((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\.(0[13456789]|1[012])\.((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\.02\.((19|[2-9]\d)\d{2}))|(29\.02\.((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))')
END;
where mydatefield is in the format DD.MM.YYYY
If that's your entire script, you're missing the DECLARE keyword at the start of your anonymous block:
DECLARE
FUNCTION is_valid_date (p_val in VARCHAR2, p_format IN VARCHAR2 )
RETURN numeric IS
l_date VARCHAR2(100);
BEGIN
l_date := TO_date( p_val, p_format );
RETURN 1;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END is_valid_date;
BEGIN
DBMS_OUTPUT.PUT_LINE(is_valid_date('20120101', 'YYYYMMDD' ));
END;
/
anonymous block completed
1
Without that you'll get a series of errors starting with
Error starting at line : 1 in command -
FUNCTION is_valid_date (p_val in VARCHAR2, p_format IN VARCHAR2 )
Error report -
Unknown Command
... which I imagine is the 'generic error' you referred to.

Stored Function in Oracle not Inserting Values into the desired table

Here is my Code given below. I am trying to add 5 parameters which the function takes into the table Employee. But I am not successful in doing it and have tried a lot of things.
Error
ORA-01858: a non-numeric character was found where a numeric was
expected ORA-06512: at "xxxxxxx.A1SF_ADDEMP", line 14
01858. 00000 - "a non-numeric character was found where a numeric was expected"
*Cause: The input data to be converted using a date format model was
incorrect. The input data did not contain a number where a number was
required by the format model.
*Action: Fix the input data or the date format model to make sure the
elements match in number and type. Then retry the operation.
Plus how do I test a Stored function that has a Insert/Update or Delete Statement in it?
Execution Statement
Select A1SF_ADDEMP('Adesh', '33', 'M', 8000, '26/03/1990')
From dual;
Code
CREATE OR REPLACE Function A1SF_ADDEMP
(pEmpName In Varchar2,
pTaxFileNo In Varchar2,
pGender In Varchar2,
pSalary In Number,
pBirthdate In Varchar2
) Return Varchar2
Is
tEmpId Number(38,0);
tBirthDate Date;
BEGIN
tEmpId := A1Seq_Emp.nextval;
tBirthdate := to_date('pBirthdate','dd/mm/yyyy');
Insert Into Employee(EmpId, EmpName, TaxFileNo, Gender, Salary, Birthdate)
Values (tEmpId, pEmpName, pTaxFileNo, pGender, pSalary, tBirthdate);
Commit;
Return null;
END;
Firstly you cannot call a function with DML in it in a select statement. You have to assign the output to a variable in a PL/SQL block, something like:
declare
l_output number;
begin
l_output := my_function(variable1, variable2);
end;
It's bad practice to do DML in a function; partly because it causes the errors you're coming across. You should use a procedure as detailed below. The other reason for this is that you're as always returning null there's no need to return anything at all!
create or replace procedure my_procedure ( <variables> ) is
begin
insert into employees( <columns> )
values ( <values > );
end;
The specific reason for your error is this line:
tBirthdate := to_date('pBirthdate','dd/mm/yyyy');
pBirthdate is already a string; by putting a ' around it you're passing the string 'pBirthdate' to the function to_date and Oracle can't convert this string into a day, month or year so it's failing.
You should write this as:
tBirthdate := to_date(pBirthdate,'dd/mm/yyyy');
You also don't need to specify number(38,0), you can just write number instead.
It is possible to return a value from a procedure using the out keyword. If we assume that you want to return empid you could write is as something like this:
create or replace procedure A1SF_ADDEMP (
pEmpName in varchar2
, pTaxFileNo in varchar2
, pGender in varchar2
, pSalary in number
, pBirthdate in varchar2
, pEmpid out number
) return varchar2 is
begin
pempid := A1Seq_Emp.nextval;
Insert Into Employee(EmpId, EmpName, TaxFileNo, Gender, Salary, Birthdate)
Values ( pEmpId, pEmpName, pTaxFileNo, pGender
, pSalary, to_date(pBirthdate,'dd/mm/yyyy');
end;
To just execute the procedure call it like this:
begin
A1SF_ADDEMP( EmpName, TaxFileNo, Gender
, Salary, Birthdate);
commit;
end;
If you want to return the empid then you can call it like this:
declare
l_empid number;
begin
l_empid := A1SF_ADDEMP( EmpName, TaxFileNo, Gender
, Salary, Birthdate);
commit;
end;
Notice how I've moved the commit to the highest level, this is to avoid committing stuff in every procedure when you might have more things you need to do.
Incidentally, if you're using Oracle 11g then there's no need to assign the value A1Seq_Emp.nextval to a variable. You can just insert it directly into the table in the values list. You, of course won't be able to return it, but you could return A1Seq_Emp.curval, as long as there's nothing else getting values from the sequence.
You should use a procedure (instead of a function) if you are not returning any values.
If you look at the line mentioned in the error message you can spot your error:
tBirthdate := to_date('pBirthdate','dd/mm/yyyy');
You are passing the string literal 'pBirthdate' to the to_date() call. But you want to pass the parameter, so it should be
tBirthdate := to_date(pBirthdate,'dd/mm/yyyy');
(note the missing single quotes arount pBirthdate).
So as a procedure the whole thing would look like this:
CREATE OR REPLACE PROCEDURE A1SF_ADDEMP
(pEmpName In Varchar2,
pTaxFileNo In Varchar2,
pGender In Varchar2,
pSalary In Number,
pBirthdate In Varchar2
)
IS
BEGIN
Insert Into Employee(EmpId, EmpName, TaxFileNo, Gender, Salary, Birthdate)
Values (A1Seq_Emp.nextval, pEmpName, pTaxFileNo, pGender, pSalary, to_date(pBirthdate,'dd/mm/yyyy'));
Commit;
END;
To run it:
execute A1SF_ADDEMP('Adesh', '33', 'M', 8000, '26/03/1990');
In your situation you need to use procedure with out parameter where your out param is your returning param that contains your desirable value. This is I think best practice in this situation when you want to use DML in select statement.
Second way to do it but its not a good practice is to use one function like yours but before return a value you need to use if statement to check what is the value and if value is what you desire to call in this if statement PRAGMA AUTONOMOUS_TRANSACTION procedure which will do your DML independently of function calling to it. For more information about pragma transactions your can read here:
http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/autonotransaction_pragma.htm
Best Regards and hope I was helpful