ORA-00904 Invalid Identifier -- Dynamic Oracle function - oracle

create or replace
FUNCTION JDT_UDC_Desc
(
V_SY IN VARCHAR2,
V_RT IN VARCHAR2,
V_KY IN VARCHAR2
)
RETURN VARCHAR2
AS
V_DL01 VARCHAR2(30);
BEGIN
EXECUTE IMMEDIATE 'select drdl01
from PRODCTL.F0005
WHERE DRSY = V_SY
AND DRRT = V_RT
AND ltrim(rtrim(drky)) =ltrim(rtrim(V_KY))'
INTO V_DL01
using V_SY,V_RT,V_KY;
END;
Compiled. I click on run and enter below values:
V_SY ='00',
V_RT = '01',
V_KY='04';
And I get below error
ORA-00904 V_KY Invalid Identifier
Can anyone help me understand the reason for this error?

You are passing the literal values 'V_SY', 'V_RT' and 'V_KY' in your statement and it's interpreting them as column names, hence the invalid identifier error. You need to use the variable placeholders like:
EXECUTE IMMEDIATE 'select drdl01
from PRODCTL.F0005
WHERE DRSY = :1
AND DRRT = :2
AND ltrim(rtrim(drky)) =ltrim(rtrim(:3))'
INTO V_DL01
using V_SY,V_RT,V_KY;

First, there does not appear to be any reason to use dynamic SQL here. It should be rare that you need to resort to dynamic SQL-- your code is going to be more efficient and more maintainable.
create or replace
FUNCTION JDT_UDC_Desc
(
V_SY IN VARCHAR2,
V_RT IN VARCHAR2,
V_KY IN VARCHAR2
)
RETURN VARCHAR2
AS
V_DL01 VARCHAR2(30);
BEGIN
select drdl01
into V_DL01
from PRODCTL.F0005
WHERE DRSY = V_SY
AND DRRT = V_RT
AND trim(drky) =trim(V_KY);
return v_dl01;
END;
Second, it would be really helpful if you picked meaningful variable names and meaningful names for your columns and tables. F0005 tells you nothing about what the table contains. v_sy and drsy tell you nothing about what the variable or column is supposed to contain. That is going to make maintaining this code far more difficult that it needs to be.

Related

What do these errors mean and how do you suggest I fix them?

I am new to learning SQL and currently learning it in class. I am trying to write a code that fulfills the following requirements:
Make a reservation: Input parameters: Hotel, guest’s name, start date, end dates, room type, date of reservation. Output: reservation ID. NOTE: Only one guest per reservation. However, the same guest can make multiple reservations.
Find a reservation: Input is the guest’s name and date, hotel ID. The output is reservation ID
I am still somewhat new to deciphering error codes and tried to look up what they mean. However, I'm still not quite sure why my code is wrong.
CREATE OR REPLACE PACKAGE hotelmanagement AS
FUNCTION make(rsrv_id VARCHAR2
,hotel_name VARCHAR2
,guest VARCHAR2
,start_date VARCHAR2
,end_date VARCHAR2
,room_type VARCHAR2
,rsrv_date VARCHAR2)
RETURN NUMBER IS
rsrv_id NUMBER;
BEGIN
SELECT rsrv_seq.nextval INTO reserve_id FROM dual;
INSERT INTO reservations
VALUES
(reserve_id, 'Four Seasons', 'Amanda', 'July-30-2019', 'Aug-8-2019',
'King', 'July-18-2019');
tot_rsrv := tot_rsrv + 1;
RETURN(rsrv_id);
END;
FUNCTION find(guest VARCHAR2
,rsrv_date VARCHAR2)
RETURN NUMBER IS
rsrv_id NUMBER;
BEGIN
SELECT rsrv_id
INTO guest
FROM reservations
WHERE rsrv_date = find_rsrv_date;
END;
RETURN(rsrv_id);
END hotelmanagement;
I have these error messages(two of them look the same?):
Error(4,1): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: begin function pragma procedure subtype type current cursor delete exists prior The symbol "begin" was substituted for "SELECT" to continue.
Error(5,1): PLS-00103: Encountered the symbol "RSRV_ID" when expecting one of the following: language
Error(5,1): PLS-00103: Encountered the symbol "RSRV_ID" when expecting one of the following: language
The requirements are a quite vague, so it is difficult to provide the desired procedure. Anyway, your code has some weak items.
Your procedure has several input parameters but you don't use them inside the procedure.
Use appropriate data types, i.e. never(!) store DATE or number values in string, i.e. VARCHAR2. Use VARCHAR2 only for string data. At least you use four digit year, which is the proper way of doing it.
RETURN command does not use brackets.
Taking all this into account your code should be more or less like this:
CREATE OR REPLACE PACKAGE BODY hotelmanagement AS
FUNCTION make( -- you can't declare variable "rsrv_id" twice
hotel_name IN VARCHAR2
,guest IN VARCHAR2
,start_date IN DATE
,end_date IN DATE
,room_type IN VARCHAR2
,rsrv_date IN DATE)
RETURN NUMBER IS
rsrv_id NUMBER;
BEGIN
INSERT INTO reservations
VALUES
(rsrv_seq.nextval, hotel_name, guest, start_date, end_date,
room_type, rsrv_date)
RETURNING reserve_id INTO rsrv_id ;
-- tot_rsrv := tot_rsrv + 1; -> I don't see any use for it, variable tot_rsrv is not declared
RETURN rsrv_id;
END;
FUNCTION find(v_guest IN VARCHAR2
,rsrv_date IN DATE) RETURN NUMBER IS
rsrv_id NUMBER;
BEGIN
SELECT rsrv_id
INTO rsrv_id
FROM reservations
WHERE rsrv_date = find_rsrv_date
and guest = v_guest; -- don't use "guest = guest" because this will select all rows.
RETURN rsrv_id;
END;
END hotelmanagement;

How to run Oracle function which returns more than one value

My test function is this
CREATE OR REPLACE FUNCTION MULTI_VAL
(MYNAME OUT EMP2017.ENAME%TYPE)
RETURN NUMBER AS
MYSAL EMP2017.SAL%TYPE;
BEGIN
SELECT SAL, ENAME INTO MYSAL, MYNAME FROM EMP2017 ;
RETURN MYSAL;
END;
/
When I run it like
variable mynm varchar2(20)
SELECT MULTI_VAL(:mynm) FROM dual;
it gives this error
ERROR at line 1:
ORA-06553: PLS-561: character set mismatch on value for parameter 'MYNAME'
The error you get now indicates a datatype mismatch.
However there is a fundamental problem with your code. We cannot use functions which have OUT parameters in SQL. So once you have fixed the datatype issue you will get this error: ORA-06572: Function MULTI_VAL has out arguments.
You can run it like this:
declare
n varchar2(20);
x number;
begin
x := multi_val(n);
end;
/
Generally, functions with OUT parameters are considered bad practice. The syntax allows them, but the usage is hard to understand. It's better to use a procedure with two OUT parameters (because we can only call the program in PL/SQL anyway) or else have the function return a user-defined type.
CREATE TABLE EMP2017(ENAME VARCHAR2(10),SAL NUMBER);
INSERT INTO EMP2017 VALUES ('SMITH',5000);
INSERT INTO EMP2017 VALUES ('JOHNS',1000);
COMMIT;
CREATE TYPE RET_MULT AS OBJECT
(ENAME VARCHAR2(10),SAL NUMBER);
CREATE TYPE T_RET_MULT AS TABLE OF RET_MULT;
CREATE OR REPLACE FUNCTION MULTI_VAL RETURN T_RET_MULT PIPELINED IS
MYSAL RET_MULT;
BEGIN
FOR I IN(SELECT SAL, ENAME FROM EMP2017) LOOP
MYSAL := RET_MULT(I.ENAME,I.SAL);
PIPE ROW(MYSAL);
END LOOP ;
RETURN ;
END;
SELECT * FROM TABLE(MULTI_VAL());
I think this question can be solved without using pipeline functions. Just like this. All pre required data as described #Sedat.Turan except function. Sorry for copy/past.
CREATE TABLE EMP2017(ENAME VARCHAR2(10),SAL NUMBER);
INSERT INTO EMP2017 VALUES ('SMITH',5000);
INSERT INTO EMP2017 VALUES ('JOHNS',1000);
COMMIT;
CREATE TYPE RET_MULT AS OBJECT
(ENAME VARCHAR2(10),SAL NUMBER);
CREATE TYPE T_RET_MULT AS TABLE OF RET_MULT;
create or replace function MULTI_VAL return T_RET_MULT is
RET_SET T_RET_MULT;
begin
select RET_MULT(ENAME, SAL) bulk collect into RET_SET from EMP2017;
return RET_SET;
end;

Stored Procedure PL SQL If String Is blank

I got a problem with Oracle Stored Procedure. The if else statement didnt check whether the string is blank or not. Or am I doing it wrong?
create or replace PROCEDURE GET_ICECREAM
(
flavour IN VARCHAR2,
toppings IN VARCHAR2,
cursorIC OUT sys_refcursor
)
AS
dynaQuery VARCHAR2(8000);
BEGIN
dynaQuery := 'SELECT price FROM tblIceCream';
IF flavour <> '' THEN
dynaQuery := dynaQuery || ' WHERE flavour LIKE '''%''' '
ENDIF
OPEN cursorIC FOR dynaQuery;
END GET_ICECREAM;
DISCLAIMER: Above is not actual stored procedure. I'm using an example to understand concept of if else and native dynamic SQL in Oracle. So that its easier for you guys to understand ;)
Hope this below snippet will help you to understand how to handle empty string and NULL values.
SET serveroutput ON;
DECLARE
lv_var VARCHAR2(100):='';
BEGIN
IF lv_var IS NULL THEN
dbms_output.put_line('is null');
ELSE
dbms_output.put_line('av');
END IF;
END;
------------------------------------OUTPUT--------------------------------------
PL/SQL procedure successfully completed.
is null
--------------------------------------------------------------------------------
SET serveroutput ON;
DECLARE
lv_var VARCHAR2(100):='';
BEGIN
IF lv_var = '' THEN
dbms_output.put_line('is null');
ELSE
dbms_output.put_line('av');
END IF;
END;
--------------------------------------output-----------------------------------
PL/SQL procedure successfully completed.
av
--------------------------------------------------------------------------------
In PL/SQL, a zero length string that is assigned to a varchar2 variable is treated as a NULL.
In your case, if argument flavour is assigned a zero length string, the line below is actually comparing a NULL to something, which is always false.
IF flavour <> '' then
Fix that line according to your business logic to take care of null values for flavour, and you'll be fine. An example fix would be:
if flavour is not null then
In Oracle, the empty string is equivalent to NULL.
So you want to do:
IF flavour IS NOT NULL THEN
However, a better solution is not to use dynamic SQL but to re-write the WHERE filter:
create or replace PROCEDURE GET_ICECREAM
(
flavour IN VARCHAR2,
topping IN VARCHAR2,
cursorIC OUT sys_refcursor
)
AS
BEGIN
OPEN cursorIC FOR
SELECT price
FROM tblIceCream
WHERE ( flavour IS NULL OR your_flavour_column LIKE '%' || flavour || '%' )
AND ( topping IS NULL or your_topping_column LIKE '%' || topping || '%' );
END GET_ICECREAM;
/
You can try like this:
IF NVL(flavour, 'NULL') <> 'NULL'

Oracle dynamic run error

I created a procedure with dynamic sql,but cannot run it successfully.
create or replace procedure getdata(string par1, results out cursor)
as
declare sqlBase varchar2(100);
begin
sqlBase := 'open '||results|| ' for select * from studetns';
end;
After running, the following error message pops up:
PLS-00306, wrong number or types of arguments in call to '||'
I just need to filter data by some parameters ,but some parameters may be null or empty,
so I need to filter dynamic. like if(par1 is not null) then ........
so here I need to use dynamic sql. in C# programe, use cursor to return result.
like here ,I use cursor type to open select statements.
but in sql editor, I get right sql statement.
Can Somebody help me with this?
Your syntax is a little bit wrong. Try with this:
create or replace procedure getdata(par1 varchar2, par2 varchar2, results out sys_refcursor)
as
begin
open results for
select *
from students
where name = nvl(par1, name)
and surname = nvl(par2, surname);
end;
Why do you need parameter par1? Better to use PL/SQL type varchar2, not string. They work the same, but varchar2 is a base data type, while string is a subtype of it.
Depending on what you want to achieve, I would try something like that:
create or replace procedure getdata(par1 varchar2, results out sys_refcursor)
as
sqlBase varchar2(100);
begin
sqlBase := 'begin open :X for select * from students;end;';
execute immediate sqlbase USING IN OUT results;
end;
You can't concatenate a cursor into a string as you tried it, that's where your error came from.
But if you could clearify your question we could help you better.

Oracle dynamic PL/SQL. I cant get it to work

So here is my code:
CREATE OR REPLACE PROCEDURE UPDATE_USER
(
updateColumn IN USERS.column_name%type,
changeStr IN VARCHAR2,
unID IN VARCHAR2
)
IS
BEGIN
EXECUTE IMMEDIATE
'UPDATE
users
SET :1 = :2
WHERE
uniqueID = :3'
USING updateColumn, changeStr, unID;
END;
/
I've searched for other answers on this and as far as I can tell this should work. However I get the error:
'Error(3,25): PLS-00302: component 'COLUMN_NAME' must be declared'
Thanks.
The error message specifies line 3, character 25, which points to column_name in the declaration of the updateColumn parameter. It appears that you are trying to pass the column name to update as a parameter, but that means that at compile time the column isn't known, so its type can't be known. This also doesn't really make sense - if it's a number column then you'd be trying to pass the column name into a numeric parameter, which wouldn't work anyway. If you don't want to declare it as a simple varchar2, you could instead use user_tab_columns.column_name%type.
But you can't dynamically set the column name in the update statement using a bind variable. It would compile, but would get an ORA-01747 on execution from the apparent name starting with a colon. You'd need to concatenate it, something like:
CREATE OR REPLACE PROCEDURE UPDATE_USER
(
updateColumn IN user_tab_columns.column_name%type,
changeStr IN VARCHAR2,
unID IN VARCHAR2
)
IS
BEGIN
EXECUTE IMMEDIATE
'UPDATE
users
SET ' || updateColumn || ' = :1
WHERE
uniqueID = :2'
USING changeStr, unID;
END;
/
But you'd need to sanitise the column name to avoid SQL injection. APC's answer to the question you linked to mentions using the DBMS_ASSERT package, for example.

Resources