ORACLE APEX PL SQL Procedure Error - oracle

I keep getting a the error: success with compilation error. What am I doing wrong with my code? I tried it in sqlfiddle but I get an invalid SQL statement error. As far as I know, this is the correct syntax for PL/SQL
create or replace PROCEDURE PRC_CALC
(W_ORDERID_IN IN NUMBER)
AS
W_PARTSERVICEID VARCHAR2(10);
W_EXIST_FLAG NUMBER(1) :=0;
W_SUBTOTAL NUMBER(9) :=0;
W_TAX NUMBER(9) :=0.07;
W_DISCOUNT NUMBER(9) :=0;
W_TOTAL NUMBER(9) :=0;
BEGIN
SELECT COUNT(*)
INTO W_EXIST_FLAG
FROM tblJobOrders
WHERE fldOrderId = W_ORDERID_IN;
IF W_EXIST_FLAG = 1 THEN
CURSOR CUR_ORDERCHARGES IS
SELECT fldPartServiceId
FROM tblOrderCharges
WHERE fldOrderId = W_ORDERID_IN;
OPEN CUR_ORDERCHARGES;
LOOP
FETCH CUR_ORDERCHARGES
INTO W_PARTSERVICEID
EXIT WHEN CUR_ORDERCHARGES%NOTFOUND;
SELECT fldPartServiceAmount, fldDiscountPercent
INTO W_SUBTOTAL, W_DISCOUNT
FROM tblPartsServices
WHERE fldPartServiceId = W_PARTSERVICEID;
W_DISCOUNT := (W_SUBTOTAL*(W_DISCOUNT*.01));
W_TAX := (W_TOTAL*W_TAX);
W_TOTAL := W_SUBTOTAL - W_DISCOUNT;
W_TOTAL := W_TOTAL + W_TAX;
htp.prn('Your subtotal is: $' ||W_SUBTOTAL||'<br>');
htp.prn('Your Discount is: $' ||W_DISCOUNT||'<br>');
htp.prn('Your Tax is: $' ||W_TAX||'<br>');
htp.prn('Your Total is: $' ||W_TOTAL||'<br>');
END LOOP;
CLOSE CUR_ORDERCHARGES;
ELSE
htp.prn('The Order Id: '||W_ORDERID_IN||' does not exist in the database');
END IF;
END;

Your variable declarations need work
W_PARTSERVICEID VARCHAR2; should have a size such as W_PARTSERVICEID VARCHAR2(250);
Your number declarations will work but are better to specify a size as well
W_EXIST_FLAG NUMBER; should be W_EXIST_FLAG NUMBER(9);
W_EXIST_ORDER_FLAG is not declared and should be as well.
As a programming practice that goes beyond your question you should check that the values coming into the procedure and in the cursor are not null or zero.
The CURSOR CUR_ORDERCHARGES should be declared with the other declarations or put inside a new DECLARE BEGIN END block
and you are missing a semi colon when you FETCH the cursor, it should be
FETCH CUR_ORDERCHARGES
INTO W_PARTSERVICEID;
EXIT WHEN CUR_ORDERCHARGES%NOTFOUND;

The W_EXIST_ORDER_FLAG used in the first query is undefined. Perhaps, you meant W_EXIST_FLAG?

Related

Show the output of a procedure in Oracle

The procedure uses the previous function to display the list of the products: num, designation and mention on the application.
SET SERVEROUTPUT ON;
CREATE OR REPLACE FUNCTION STORE(num_produit IN INTEGER) RETURN VARCHAR AS
N INTEGER := 0;
incre INTEGER := 0;
BEGIN
SELECT SUM(qte) INTO N FROM Ligne_Fact WHERE num_produit = produit;
IF N > 15 THEN
RETURN 'fort';
ELSIF N > 11 THEN
RETURN 'moyen';
END IF;
RETURN 'faible';
END;
/
CREATE OR REPLACE PROCEDURE SHOW_PRODUITS IS
SOME_VAR VARCHAR2(256);
BEGIN
SELECT num, designation, STORE(num) INTO SOME_VAR FROM Produit;
dbms_output.enable();
dbms_output.put_line('result : '|| SOME_VAR);
END;
/
BEGIN
SHOW_PRODUITS;
END;
/
I am sure that all the tables are filled with some dummy data, but I am getting the following error:
Function STOCKER compiled
Procedure AFFICHER_PRODUITS compiled
LINE/COL ERROR
--------- -------------------------------------------------------------
4/4 PL/SQL: SQL Statement ignored
4/56 PL/SQL: ORA-00947: not enough values
Errors: check compiler log
Error starting at line : 28 in command -
BEGIN
AFFICHER_PRODUITS;
END;
Error report -
ORA-06550: line 2, column 5:
PLS-00905: object SYSTEM.SHOW_PRODUITS is invalid
ORA-06550: line 2, column 5:
PL/SQL: Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation error.
The first major mistake you've made is to create your objects in SYSTEM schema. It, just like SYS, are special and should be used only for system maintenance. Create your own user and do whatever you're doing there.
As of your question: select returns 3 values, but you're trying to put them into a single some_var variable. That won't work. Either add another local variables (for num and designation), or remove these columns from the select:
CREATE OR REPLACE PROCEDURE SHOW_PRODUITS IS
SOME_VAR VARCHAR2(256);
BEGIN
SELECT STORE(num) INTO SOME_VAR FROM Produit; --> here
dbms_output.enable();
dbms_output.put_line('result : '|| SOME_VAR);
END;
/
Code, as you put it, presumes that produit contains a single record (it can't be empty nor it can have 2 or more rows because you'll get various errors).
Maybe you wanted to access all rows; in that case, consider using a loop, e.g.
CREATE OR REPLACE PROCEDURE SHOW_PRODUITS IS
SOME_VAR VARCHAR2(256);
BEGIN
FOR cur_r IN (SELECT num, designation, STORE(num) some_var FROM Produit) LOOP
dbms_output.put_line(cur_r.num ||', '|| cur_r.designation ||', result : '|| cur_r.some_var);
END LOOP;
END;
/
Then
set serveroutput on
BEGIN
SHOW_PRODUITS;
END;
/
You are trying to compile some stored routine which calls another stored routine named AFFICHER_PRODUITS and that routine calls SHOW_PRODUITS but SHOW_PRODUITS does not compile, hence the error. (By the way, it is recommended not to create your own stored routines in the SYSTEM schema.)
SHOW_PRODUITS does not compile because of this line:
SELECT num, designation, STORE(num) INTO SOME_VAR FROM Produit;
It appears that you want to get the query results as a string. In order to do that, you need to concatenate the column values, i.e.
SELECT num || designation || STORE(num) INTO SOME_VAR FROM Produit;
Of-course if all you want to do is display the query results, using DBMS_OUTPUT, you can declare a separate variable for each column.
CREATE OR REPLACE PROCEDURE SHOW_PRODUITS IS
SOME_NUM Produit.num%type;
SOME_DES Produit.designation%type;
SOME_VAR VARCHAR2(6);
BEGIN
SELECT num
,designation
,STORE(num)
INTO SOME_NUM
,SOME_DES
,SOME_VAR
FROM Produit;
dbms_output.enable();
dbms_output.put_line('result : ' || SOME_NUM || SOME_DES || SOME_VAR);
END;
Note that if the query returns more than one row, you will [probably] need to use a cursor.
CREATE OR REPLACE PROCEDURE SHOW_PRODUITS IS
SOME_NUM Produit.num%type;
SOME_DES Produit.designation%type;
SOME_VAR VARCHAR2(6);
--
CURSOR c1 IS
SELECT num, designation, STORE(num) FROM Produit;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO SOME_NUM, SOME_DES, SOME_VAR;
EXIT WHEN c1%NOTFOUND;
dbms_output.put_line('result : ' || SOME_NUM || SOME_DES || SOME_VAR);
END LOOP;
CLOSE c1;
END;

Oracle read and return data from cursor

I'm trying to create a stored procedure in Oracle that has one input parameter and one output variable and, in case of results, return a dataset to my .Net Application. The main issue is that I can't change the signature of the procedure and need to do if condition to validate if exist records or not.
The main issue that i've being struggled is with cursors (to execute and return the information), and to count the results of the select.
Here is an example of what i'm doing to try to retrieve the data.
CREATE PROCEDURE SP_Testing (v_input IN VARCHAR2(50), v_OutID NUMBER(1))
AS
TYPE v_record_botoes IS RECORD (
v_dummy_col1 VARCHAR2(50),
v_dummy_col2 VARCHAR2(250)
);
TYPE table_botoes IS TABLE OF v_record_botoes;
tt_botoes table_botoes;
v_ref_cursor SYS_REFCURSOR;
CURSOR v_cursor IS
(SELECT dt.v_dummy_col1,
dt.v_dummy_col2
FROM dummy_table dt
WHERE v_dummy_col3 = v_input);
v_check NUMBER;
BEGIN
tt_botoes := table_botoes();
v_check := 0;
FOR v_row IN v_cursor
LOOP
tt_botoes.extend;
tt_botoes(tt_botoes.COUNT) := v_row;
END LOOP;
v_check := tt_botoes.COUNT;
-- condition that need to know the nr of records of the select
IF v_check = 0 THEN
v_OutID := 0;
ELSE
v_OutID := 1;
OPEN v_ref_cursor FOR
SELECT *
FROM tt_botoes; -- also tryed "FROM TABLE (tt_botoes)" and "FROM TABLE (cast(tt_botoes AS table_botoes))"
-- return dataset to .net application
DBMS_SQL.RETURN_RESULT(v_ref_cursor)
END IF;
END;
Already tryed to convert the v_cursor into a sys_refcursor to be outputed by the DBMS_SQL package but didn't get anywhere.
Also i've tried to create a temporary table to hold the information, but then have a concurrency issue.
Any idea what i'm doing wrong, or any other possible solution to solve this issue?
Thanks in advance
Completely untested because I do not have the environment to test it but I would structure this quite differently, see below (I am assuming that the missing out in the specification is just a typo)
CREATE PROCEDURE SP_Testing (v_input IN VARCHAR2(50), v_OutID **out** NUMBER(1))
AS
v_ref_cursor SYS_REFCURSOR;
v_check NUMBER;
BEGIN
select count(1)
into v_check
from dummy_table dt
WHERE v_dummy_col3 = v_input
-- condition that need to know the nr of records of the select
IF v_check = 0 THEN
v_OutID := 0;
ELSE
v_OutID := 1;
OPEN v_ref_cursor FOR
SELECT dt.v_dummy_col1,
dt.v_dummy_col2
FROM dummy_table dt
WHERE v_dummy_col3 = v_input
-- return dataset to .net application
DBMS_SQL.RETURN_RESULT(v_ref_cursor)
END IF;
END;

How to escape a round bracket '(' in SQL?

I am trying to use reference cursor for a sql query but I think I am missing >escape notation somewhere. I have already escaped " ' " but I am unsure about >the round brackets.
I am getting "international_flag : invalid identifier" error at open ref_cursor statement. I have tried a bunch of things to escape round brackets because I think that is why it is not picking the variable international_flag. Any leads will be much appreciated.
declare
international_flag varchar2(4) := 'Y';
term_code varchar(8) := '201709';
type stu_ref_cursor is ref cursor;
ref_cursor stu_ref_cursor;
ref_cursor_select_statement varchar2(1000);
begin
ref_cursor_select_statement :=
'Select
CONFID_MSG,
ETHNIC_CODE,
STUDENT_NAME,
POTSDAM_ID(STUDENT_PIDM),
CLASS,
LEVL_CODE,
AGE,
BIRTHDATE,
fp_get_coll_box(STUDENT_PIDM),
f_get_on_campus_email_addr(STUDENT_PIDM),
RESD_IND,
STUDENT_PIDM,
REG_HRS,
SGB_TERM_ADMIT,
GENDER
From SEM_REG_STUDENT_NONGPA
Where REG_TERM = term_code
And STATUS = ''AS''
And REG_TERM_STATUS = ''Y''
And
(
international_flag = ''N''
Or
(international_flag = ''Y'' And f_international_student_natn(STUDENT_PIDM) Is Not NULL)
Or
(international_flag = ''U'' and CITIZEN = ''Y'')
)
Order By STUDENT_NAME';
open ref_cursor for ref_cursor_select_statement;
end;
That isn't how you reference PL/SQL variables in dynamic SQL. You need to use placeholders prefixed by a colon, and supply the variable with the USING clause. That can mean repetition where, as in this case, you use the same variable several times. You'll need to put in three placeholders and pass in the same variable three times (ie USING international_flag,international_flag,international_flag)
DECLARE
TYPE EmpCurTyp IS REF CURSOR; -- define weak REF CURSOR type
emp_cv EmpCurTyp; -- declare cursor variable
my_ename VARCHAR2(15);
my_sal NUMBER := 1000;
BEGIN
OPEN emp_cv FOR -- open cursor variable
'SELECT ename, sal FROM emp WHERE sal > :s' USING my_sal;
...
END;
PS. It is better to prefix variables (often with a v_ but some people go fo l_ for local and g_ for global etc) to make it more obvious what is a column and what is a variable.
The beauty of dynamic sql is that you never get to know the error as it gives run time error only. The binding of variables should be check properly before constructing a dynamic sql. Here there are two variables like "TERM_CODE" and "INTERNTIONAL_FLAG". Hope the below snippet helps.
DECLARE
international_flag VARCHAR2(4) := 'Y';
TERM_CODE VARCHAR(8) := '201709';
ref_cursor sys_refcursor;
ref_cursor_select_statement VARCHAR2(1000);
BEGIN
ref_cursor_select_statement := 'Select
CONFID_MSG,
ETHNIC_CODE,
STUDENT_NAME,
POTSDAM_ID(STUDENT_PIDM),
CLASS,
LEVL_CODE,
AGE,
BIRTHDATE,
fp_get_coll_box(STUDENT_PIDM),
f_get_on_campus_email_addr(STUDENT_PIDM),
RESD_IND,
STUDENT_PIDM,
REG_HRS,
SGB_TERM_ADMIT,
GENDER
From SEM_REG_STUDENT_NONGPA
Where REG_TERM = '''||term_code||'''
And STATUS = ''AS''
And REG_TERM_STATUS = ''Y''
And
('''|| international_flag||''' = ''N''
Or
('''||international_flag||''' = ''Y'' And f_international_student_natn(STUDENT_PIDM) Is Not NULL)
Or
('||
international_flag||' = ''U'' and CITIZEN = ''Y'')
)
Order By STUDENT_NAME';
OPEN ref_cursor FOR ref_cursor_select_statement;
END;
/

Oracle PL/SQL dynamic if statement global vars

I'm having trouble with dynamic sql, Issue is (I think) reading and setting global variable. Here's what I have and any help at all is greatly appreciated. Please let me know if you need table data too although I have included the data in comments.
CREATE OR REPLACE PACKAGE data_load
IS
curr_rec NUMBER;
curr_rule VARCHAR2(200);
curr_sql VARCHAR2(4000);
curr_sql_two VARCHAR2(4000);
curr_data_element VARCHAR2 (200);
curr_rule_text VARCHAR2(200);
curr_error_code VARCHAR2(10);
curr_error_flag VARCHAR2(10);
curr_flag_val NUMBER;
v_check NUMBER;
v_ID NUMBER;
cur_hdl INT ;
rows_processed NUMBER;
PROCEDURE check_rules;
END data_load;
The package body:
create or replace PACKAGE BODY data_load IS
PROCEDURE check_rules IS
CURSOR c1
IS
SELECT * FROM STAGING_TABLE where rownum < 3;
CURSOR c2
IS
SELECT * FROM ERROR_CODES WHERE rule_text IS NOT NULL AND status =1;
BEGIN
FOR rec1 IN c1
LOOP
FOR rec2 IN c2
LOOP
curr_data_element := 'rec1.'||rec2.data_element; --- this results in value "rec1.SHIP_FROM_ACCOUNT_ORG_CODE" without quotes
curr_rule_text := rec2.rule_text; --- this value is "is not null" without quotes
curr_error_flag := rec2.error_flag; --this value is "FLAG_03" without quotes
curr_flag_val := to_number(rec2.error_code); --- this value is 31
curr_sql :='begin if :curr_data_element '||curr_rule_text||' then update table_with_column_FLAG_03 set '||curr_error_flag ||' = 0; else update table_with_column_FLAG_03 set '||curr_error_flag ||' = '||curr_flag_val||'; end if; end;';
dbms_output.put_line(curr_sql); -- results in "begin if :curr_data_element is null then update table_with_column_FLAG_03 set FLAG_03 = 0; else update table_with_column_FLAG_03 set FLAG_03 = 31; end if; end;"
EXECUTE IMMEDIATE curr_sql USING curr_data_element ; -- this always updates the column with 31 even when curr_data_element/ rec1.SHIP_FROM_ACCOUNT_ORG_CODE is null and that's the problem
COMMIT;
END LOOP;
curr_rec := curr_rec+1;
END LOOP;
dbms_output.put_line(curr_rec);
END check_rules;
END data_load;
You've already highlighted the problem really:
curr_data_element := 'rec1.'||rec2.data_element; --- this results in value "rec1.SHIP_FROM_ACCOUNT_ORG_CODE" without quotes
You can't refer to cursor columns dynamically. You are creating a string with value 'rec1.SHIP_FROM_ACCOUNT_ORG_CODE'; there is no mechanism to evaluate what that represents. You can't, for instance, try to dynamically select that from dual because the rec1 is not in scope for a SQL call, even dynamically.
When you bind that string value it is never going to be null. You are using that string, not the value in the outer cursor that it represents, and essentially you cannot do that.
The simplest way to deal with this, if you have a reasonably small number of columns in your staging table that might appear as the rec2.data_element value, is to use a case expression to assign the appropriate actual rec1 column value to the curr_data_element variable, based on the rec2.data_element value:
...
BEGIN
FOR rec1 IN c1
LOOP
FOR rec2 IN c2
LOOP
curr_data_element :=
case rec2.data_element
when 'SHIP_FROM_ACCOUNT_ORG_CODE' then rec1.SHIP_FROM_ACCOUNT_ORG_CODE
when 'ANOTHER_COLUMN' then rec1.ANOTHER_COLUMN
-- when ... -- repeat for all possible columns
end;
curr_rule_text := rec2.rule_text;
...
If you have a lot of columns you could potentially do that via a collection but it may not be worth the extra effort.
The curr_sql string stays the same, all that's changing is that you're binding the actual value from the relevant rec1 column, rather than never-null string you were forming.

How can this piece of PLSQL be made to compile?

I need to return the names of employees in string format for all those employees whose manager ID depends on the passed parameter. When I compile the function I get an error. Here is the function code:
create or replace function Employee(v_manid IN employees.manager_id%type)
return varchar2
AS
cursor cur_emp is select last_name from employees where manager_id = v_manid;
v_names varchar2(10);
begin
for emp_rec in cur_emp
loop
v_name = v_name || emp_rec.last_name ||', ';
end loop;
return v_name
end;
/
The error is:
Error(8,8): PLS-00103: Encountered the symbol "=" when expecting one
of the following: := . ( # % ; Error(8,44): PLS-00103:
Encountered the symbol ";" when expecting one of the following: )
, * & - + / at mod remainder rem and or ||
Could anyone help me with this?
As stated in the other answers the reason why your function won't compile is threefold.
You've declared the variable v_names and are referencing it as v_name.
The assignment operator in PL/SQL is :=, you're using the equality operator =.
You're missing a semi-colon in your return statement; it should be return v_name;
It won't stop the function from compiling but the variable v_names is declared as a varchar2(10). It's highly unlikely that when a manager with multiple subordinates all their last names will fit into this. You should probably declare this variable with the maximum size; just in case.
I would like to add that you're doing this a highly inefficient way. If you were to do the string aggregation in SQL as opposed to a PL/SQL loop it would be better. From 11g release 2 you have the listagg() function; if you're using a version prior to that there are plenty of other string aggregation techniques to achieve the same result.
create or replace function employee ( p_manid in employees.manager_id%type
) return varchar2 is
v_names varchar2(32767); -- Maximum size, just in case
begin
select listagg(lastname, ', ') within group ( order by lastname )
into v_names
from employees
where manager_id = p_manid;
return v_names;
exception when no_data_found then
return null;
end;
/
Please note a few other changes I've made:
Prepend a different letter onto the function parameter than the variable to make it clear which is which.
Add in some exception handling to deal with there being no data for that particular manager.
You would have returned , if you had no data I return NULL. If you want to return a comma instead simply put this inside the exception.
Rather than bother to create a cursor and loop through it etc I let Oracle do the heavy lifting.
It's rather curious that you would want to return a comma delimited list as there is little that you would be able to do with it in Oracle afterwards. It might be more normal to return something like an array or an open cursor containing all the surnames. I assume, in this answer, that you have a good reason for doing what you are.
There are a couple of things to be noted.
Declared as v_names but used as v_name
Assignemnt should be like v_name := v_name || emp_rec.last_name ||
', ';
v_name is declared with size of 10, it would be too small and would
give an error when you execute, so you could declare as
v_name employees.last_name%TYPE;
You could create your function as
CREATE OR REPLACE FUNCTION employee (v_manid IN employees.manager_id%TYPE)
RETURN VARCHAR2
AS
v_name employees.last_name%TYPE;
CURSOR cur_emp
IS
SELECT last_name
FROM employees
WHERE manager_id = v_manid;
BEGIN
FOR emp_rec IN cur_emp
LOOP
v_name := v_name || emp_rec.last_name || ', ';
END LOOP;
RETURN v_name;
END;
/
I guess you should use := instead of =
like
v_name := v_name || emp_rec.last_name ||', ';
one more thing you also need to add semicolon ; at the end of return v_name like
return v_name;

Resources