what's wrong with if statement? - oracle

I'am trying to use more than one if condition in PL\SQL, and it gives me an error:
ORA-06550: line 16, column 5:
PLS-00103: Encountered the symbol "LOOP" when expecting one of the following:
if
here's my code:
declare
price_var number;
st_numb number;
co_pr number;
cursor student_count is select STUDENT_NUMBER,COURSE_PRICE from COURSES;
begin
open student_count;
loop
fetch student_count into st_numb,co_pr;
if st_numb<10 then
update COURSES set COURSE_PRICE=co_pr*1.05;
elseif st_numb>10 then
update COURSES set COURSE_PRICE=co_pr*1.07;
end if;
exit when student_count%notfound;
end loop;
end
can you tell me where is the error ?
thanks.

First, I think in PL/SQL it's "elsif" and not "elseif". Then (I dont know if this is important or not), maybe you need the parenthesis around the conditions, I don't know.
Source: https://www.tutorialspoint.com/plsql/plsql_if_then_elsif.htm

You would need elsif, not elseif and also ; after end.
Try this one corrected:
declare
price_var number;
st_numb number;
co_pr number;
cursor student_count is
select student_number
,course_price
from courses;
begin
open student_count;
loop
fetch student_count
into st_numb
,co_pr;
if st_numb < 10 then
update courses set course_price = co_pr * 1.05;
elsif st_numb > 10 then --elsif, not elseif
update courses set course_price = co_pr * 1.07;
end if;
exit when student_count%notfound;
end loop;
end; --also need ";" after end

Just to add to massko's answer -
The ordinary Cursor FOR loop is simpler, more efficient and more reliable than the explicit open-fetch-exit-close. Also, you have to specify which row to update within the loop, otherwise you will update every row in the table. (And although the compiler doesn't care how you lay out your code or whether you put random words in uppercase, it's good to get into the habit of coding neatly.) Therefore as a first refactor we get this:
begin
for r in (
select course_id -- Assuming courses have a unique ID
, student_number, course_price
from courses
)
loop
if r.student_number < 10 then
update courses set course_price = r.course_price * 1.05
where course_id = r.course_id;
elsif r.student_number > 10 then
update courses set course_price = r.course_price * 1.07
where course_id = r.course_id;
end if;
end loop;
end;
But then why repeat the update statement twice when all that changes is the multiplication factor, and why we are looping through rows we don't do anything with? We can therefore simplify it a stage further:
begin
for r in (
select course_id, student_number, course_price
from courses
where student_number <> 10
)
loop
update courses
set course_price = r.course_price *
case
when r.student_number < 10 then 1.05
when r.student_number > 10 then 1.07
end
where course_id = r.course_id;
end loop;
end;
Then again, why do we even need a laborious row-by-row approach when we can do it in one shot?
begin
update courses c
set course_price = r.course_price *
case
when c.student_number < 10 then 1.05
when c.student_number > 10 then 1.07
end
where c.student_number <> 10;
end;
btw I don't know your data model, but storing a count of the number of students within each course record doesn't seem a reliable approach.

Related

how do I use if condition in cursor because our professor don't allow us use where clause in the select statement

Our question is showing all the countries that have names that are exactly 5 letter long. This is the cursor code and I want add if condition into it.
declare
cursor cursor_full is select * from country_cont;
begin
for counter in cursor_full
loop
dbms_output.put_line(counter.country|| ' ' || counter.continent);
end loop;
end;
However my professor said that you can't using where clause within the select statement and you should display all the countries and continent.
so i tried this code:
declare
country varchar(50);
cursor cursor_full is select * from country_cont;
begin
if length(country)=5 then
for counter in cursor_full
loop
dbms_output.put_line(counter.country|| ' ' || counter.continent);
end loop;
end if;
end;
the script output show that PL/SQL procedure successfully completed but nothing return in DBMS output
Hope someone can help me, I spent whole night to think about it,please!
Variable country doesn't contain any value, it is null so if condition is never true and loop is never executed. Sample data would help; meanwhile, see if this helps.
begin
for cur_r in (select * from country_cont) loop
if length(cur_r.country) > 5 then
dbms_output.put_line(cur_r.country|| ' ' || cur_r.continent);
end loop;
end;
Don't forget to set serveroutput on.

Declare a cursor to use it after begin

I have a project where i have to check if how many products are left to sell from a company for certain clients. A client can have many companies, also i have to refuse when a client or a product don't exist.
I have a table where i have clients and companies, then i got another where i have companies and products. I'm trying to create cursors to manage on the "companie-product" table, just the companies that the client can buy from, but when i declare a cursor it says "it's not a cursor" i've tryed the %rowtype, also the %type, and neither work. Does anyone know how i can fix it?
CREATE OR REPLACE PROCEDURE Transaccion
IS
my_cantidaRechazada NUMBER;
CURSOR peti
IS
SELECT idCliente, idProducto, cantidadPedido
FROM TABLAS_COMP.peticiones
ORDER BY idCliente ASC;
CURSOR empresaCliente
IS
SELECT *
FROM TABLAS_CL.empresacliente
ORDER BY tablas_cl.empresacliente.empresa;
empC empresaCliente%ROWTYPE;
CURSOR empresaProducto (vempresa NUMBER)
IS
SELECT *
FROM TABLAS_PRO.empresaproducto
WHERE empresa = vempresa
ORDER BY tablas_pro.empresaproducto.empresa ASC;
empP empresaProducto%ROWTYPE;
BEGIN
FOR cont IN peti
LOOP
IF existecliente (cont.idCliente) = 0
THEN
my_cantidaRechazada := cont.cantidadPedido;
INSERT INTO TABLAS_COMP.rechazados
VALUES (cont.idCliente,
cont.idProducto,
cont.cantidadPedido,
my_cantidaRechazada);
ELSIF existeproducto (cont.idProducto) = 0
THEN
my_cantidaRechazada := cont.cantidadPedido;
INSERT INTO TABLAS_COMP.RECHAZADOS
VALUES (cont.idCliente,
cont.idProducto,
cont.cantidadPedido,
my_cantidaRechazada);
END IF;
SELECT *
INTO empC
FROM TABLAS_CL.empresacliente
WHERE Cliente = cont.idCliente
ORDER BY empresa ASC;
FOR empP IN empC
LOOP -- (here's where the error is showed, it says "empC it's not a cursor")
SELECT *
INTO empP
FROM TABLAS_PRO.empresaproducto
WHERE Empresa = empC.Empresa;
END LOOP;
END LOOP;
END Transaccion;
Thanks in advance, David.
It would help if you specified oracle error exactly, along with the ORA-XXXXX error code. Saying it in your words can be ambiguous.
Anyway: what you indicated is wrong, really. Should be
-- wrong: for empP in empC loop
for empP in empresaProducto loop
...
end loop;
because empP is declared as empresaProducto cursor variable.
Though, SELECT you put into the loop is meaningless - you already have empP, so - why would you insert into it again? Think it over.

PL/SQL If statement, cursors, and a record set. How to use an IF statement after I use the Cursor?

I am wondering if I am going about this the right way.
My main issue that compiler gives is for this line
IF SELECT 1 FROM works WHERE an_employee.employee_name IN works.manager_name THEN
Error(17,8): PLS-00103: Encountered the symbol "SELECT" when expecting one of the following: ( - + case mod new not null continue avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date pipe
What I am trying to do is use a cursor that detects the first condition if they work in a company that is in that city. In this example in my table it will give 2 companies, and about 7 or 8 employees. Then I put that into my variable an_employee. What I am trying to do is use that employee then to see if they are a manager from my manages table which has multiple rows/tuples. Not everyone is a manager. How can I see if my employee_name is in the list of manager_name?
Do I declare another cursor for a manager and then do a nested loop?
Can I use my existing cursor and do a select query to get the list of managers from the table manages.manager_name? If I do that, how can I use it in the IF statement as my condition?
-- Give all employees that work in a company located in city X
-- a Y percent raise if they are managers and
-- a Z percent raise if they are not a manager
-- X, Y, and Z will be the three parameters for the stored procedure.
-- Build / compile a stored procedure
CREATE OR REPLACE PROCEDURE give_raises(X company.city%TYPE, Y NUMBER, Z NUMBER) IS
an_employee works.employee_name%TYPE;
-- cursor declaration
cursor Cursor1 IS
select works.employee_name
from works
where works.company_name IN (select company_name from company where city = 'London');
BEGIN
SELECT manager_name INTO managers FROM manages;
OPEN Cursor1;
LOOP
FETCH Cursor1 INTO an_employee;
EXIT WHEN Cursor1%NOTFOUND;
-- is a manager give Y percent raise
IF SELECT 1 FROM works WHERE an_employee.employee_name IN works.manager_name THEN
update works
set works.salary = works.salary + (works.salary * Y)
where works.employee_name = an_employee.employee_name;
ELSE -- is not a manager give Z percent raise
update works
set works.salary = works.salary + (works.salary * Z)
where works.employee_name = an_employee.employee_name;
END IF;
END LOOP;
CLOSE Cursor1;
END;
Also you should know. I am using Oracle, Oracle Sql Developer and the IDE.
If works on a logical condition and does not support Select statements in the condition.
You need to rework your code like this
SELECT count(*)
INTO v_value
FROM works
WHERE an_employee.employee_name = works.manager_name;
IF v_value = 1 THEN
--do some stuff
ELSE
--do some other stuff
END IF;
If i understand your problem correctly you are trying to identify whether an employee is manager or not based on thatsalary is computed. Hope below snippet helps.
CREATE OR REPLACE PROCEDURE give_raises(
X company.city%TYPE,
Y NUMBER,
Z NUMBER)
AS
managers PLS_INTEGER;
BEGIN
FOR an_employee IN
(SELECT works.employee_name
FROM works
WHERE works.company_name IN
(SELECT company_name FROM company WHERE city = 'London'
)
)
LOOP
SELECT COUNT(1)
INTO managers
FROM manages m
WHERE m.manager_name = an_employee.employee_name;
-- is a manager give Y percent raise
IF managers <> 0 THEN
UPDATE works
SET works.salary = works.salary + (works.salary * Y)
WHERE works.employee_name = an_employee.employee_name;
ELSE -- is not a manager give Z percent raise
UPDATE works
SET works.salary = works.salary + (works.salary * Z)
WHERE works.employee_name = an_employee.employee_name;
END IF;
END LOOP;
END;
Your problem is essentially the same than e.g. in a question posted yesterday. PL/SQL if statement expects a boolean expression not a query result set.
A good practice is to encapsulate the query to a function returning a suitable value.
Example:
SQL> !cat so53.sql
declare
function is_foo_1(p_foo in varchar2) return boolean is
v_exists number;
begin
select count(*)
into v_exists
from dual
where dummy = p_foo
and rownum = 1
;
return
case v_exists
when 1 then true
else false
end;
end;
function is_foo_2(p_foo in varchar2) return number is
v_exists number;
begin
select count(*)
into v_exists
from dual
where dummy = p_foo
and rownum = 1
;
return v_exists;
end;
begin
-- is_foo_1 returns a boolean value than is a valid boolean expression
if is_foo_1('X')
then
dbms_output.put_line('1:X');
end if;
if not is_foo_1('Y')
then
dbms_output.put_line('1:not Y');
end if;
-- is_foo_2 returns a number that is not a valid boolean expression (PL/SQL
-- doesn't have implicit type conversions) so one have to use an operator
-- (in this example `=`-operator) to construct an explicit boolean
-- expression
if is_foo_2('X') = 1
then
dbms_output.put_line('2:X');
end if;
if is_foo_2('Y') = 0
then
dbms_output.put_line('2:not Y');
end if;
end;
/
Example run:
SQL> #so53.sql
1:X
1:not Y
2:X
2:not Y
PL/SQL procedure successfully completed.
SQL>

pl/sql loop records select oracle plsql

I have a select statement that I am trying to loop over and increment a variable based on the condition of the select statement, then return the variable as an out so I can do something with it in some front end code. I am using oracle 11g and I am seeing a few ways I can do this... but I am not sure which is the best way. I have some of what I am trying to do below, but again stopped because of confusion.
First I am setting my proc and 'in variable'
PROCEDURE SEEKER (pMonkeyID IN Number, vMarkCounter OUT Number)
AS
BEGIN
CURSOR seeker_cur IS
Select Mokney_approved, Monkey_vaulted
from MonkeyBookApps
where MonkeyID = pMonkeyID
and Monkey_doc_type = 'BANANA'
order by docu_approv_timestamp,monkey_doc_type,monkey_doc_approved desc
OPEN seeker_cur;
begin
OPEN Seeker_cur;
vMarkCounter := 0;
Here is the part I am not sure about. Should I loop and then exit if the condition is not met or should I do an if statement and somehow determine if there is a record that could be greater than one? If so how would that work? Is there a benefit to doing one way over the other? So... I am going to sudo-code what I am trying to do (below):
FOR (however many records) in Seeker_cur
IF seeker_cur (not found) or (returns no records)
EXIT or (break for loop);
ELSE
LOOP
vMarkCounter := vMarkCounter + 1;
EXIT WHEN seeker_cur is out of records (somehow)
END IF;
END LOOP;
END;
END SEEKER;
I am sure there are a few ways to do this. What ways would you suggest?
why dont you use implicit cursor , it will open and close itself:
DECLARE
CURSOR seeker_cur IS
Select Mokney_approved, Monkey_vaulted
from MonkeyBookApps
where MonkeyID = pMonkeyID
and Monkey_doc_type = 'BANANA'
order by docu_approv_timestamp,monkey_doc_type,monkey_doc_approved desc;
vMarkCounter number:=0;
BEGIN
FOR i IN seeker_cur
LOOP
vMarkCounter := vMarkCounter+1;
END LOOP;
dbms_output.put_line(vMarkCounter);
END;
It seems to me that the solution your problem might be as simple as this:
SELECT COUNT(*)
INTO l_some_local_variable
FROM monkey_book_apps
WHERE monkey_id = p_monkey_id
AND monkey_doc_type = 'BANANA';
RETURN l_some_local_variable;
Avoiding PL/SQL loops and using the simplest SQL possible is (almost always) the most efficient way. Tom Kyte calls the row-by-row execution of LOOPs "slow-by-slow".

How to find number of rows in cursor

I would like to find the number of rows in a cursor. Is there a keyword that can help? Using COUNT, we have to write a query. Any help will be greatly appreciated.
The cursor_variable.%ROWCOUNT is the solution. But its value will be 0 if you check it after opening. You need to loop through all the records, to get the total row count. Example below:
DECLARE
cur sys_refcursor;
cur_rec YOUR_TABLE%rowtype;
BEGIN
OPEN cur FOR
SELECT * FROM YOUR_TABLE;
dbms_output.put_line(cur%rowcount);--returning 0
LOOP
FETCH cur INTO cur_rec;
EXIT WHEN cur%notfound;
dbms_output.put_line(cur%rowcount);--will return row number beginning with 1
dbms_output.put_line(cur_rec.SOME_COLUMN);
END LOOP;
dbms_output.put_line('Total Rows: ' || cur%rowcount);--here you will get total row count
END;
/
You must open the cursor and then fetch and count every row. Nothing else will work.
You can also use BULK COLLECT so that a LOOP is not needed,
DECLARE
CURSOR c
IS SELECT *
FROM employee;
TYPE emp_tab IS TABLE OF c%ROWTYPE INDEX BY BINARY_INTEGER;
v_emp_tab emp_tab;
BEGIN
OPEN c;
FETCH c BULK COLLECT INTO v_emp_tab;
DBMS_OUTPUT.PUT_LINE(v_emp_tab.COUNT);
CLOSE c;
END;
/
Edit: changed employee%ROWTYPE to c%ROWTYPE
You can use following simple single line code to print cursor count
dbms_output.put_line(TO_CHAR(cur%rowcount));
This should work for you
DECLARE
CURSOR get_data_ IS
SELECT *
FROM table_abc_
WHERE owner = user_; -- your query
counter_ NUMBER:= 0;
BEGIN
FOR data_ IN get_data_ LOOP
counter_ := counter_ + 1;
END LOOP;
dbms_output.put_line (counter_);
END;
DECLARE #STRVALUE NVARCHAR(MAX),
#CREATEDDATE DATETIME,
#STANTANCEVALUE NVARCHAR(MAX),
#COUNT INT=0,
#JOBCODE NVARCHAR(50)='JOB00123654',
#DATE DATETIME=GETDATE(),
#NAME NVARCHAR(50)='Ramkumar',
#JOBID INT;
CREATE TABLE #TempContentSplitValue (ITEMS NVARCHAR(200))
SELECT #JOBID = i.Id FROM JobHeader_TBL i WHERE Id=1201;
IF EXISTS (SELECT 1 FROM JobHeader_TBL WHERE Id=#JOBID)
BEGIN
SELECT #STRVALUE= Description from ContentTemplate_TBL where Id=1
INSERT INTO #TempContentSplitValue SELECT * FROM dbo.split(#STRVALUE, '_')
SET #STRVALUE=''
DECLARE db_contentcursor CURSOR FOR SELECT ITEMS FROM #TempContentSplitValue
OPEN db_contentcursor
FETCH NEXT FROM db_contentcursor
INTO #STANTANCEVALUE
WHILE (##FETCH_STATUS = 0)
BEGIN
SET #STRVALUE += #STANTANCEVALUE + 'JOB00123654'
SET #COUNT += 1
SELECT #COUNT
FETCH NEXT FROM db_contentcursor INTO #STANTANCEVALUE
END
CLOSE db_contentcursor
DEALLOCATE db_contentcursor
DROP TABLE #TempContentSplitValue
SELECT #STRVALUE
END
Here I am trying to count the total number of customers with age greater than 25. So store the result in the cursor first. Then count the size of the cursor inside the function or in the main begin itself.
DECLARE
cname customer24.cust_name%type;
count1 integer :=0;
CURSOR MORETHAN is
SELECT cust_name
FROM customer24
where age>25;
BEGIN
OPEN MORETHAN;
LOOP
FETCH MORETHAN into cname;
count1:=count1+1;
EXIT WHEN MORETHAN%notfound;
END LOOP;
-- dbms_output.put_line(count1);
dbms_output.put_line(MORETHAN%ROWCOUNT);
CLOSE MORETHAN;
END;
There is a possible work around that may be useful/needed because of the overhead of accessing a database server over a network (e.g., when using Ajax calls)
Consider this:
CURSOR c_data IS
SELECT per_first_name , null my_person_count
FROM person
UNION
SELECT null as per_first_name , count( distinct per_id ) as my_person_count
FROM person
order by my_person_count ;
The first row fetched has the count of records. One MUST add specific columns fetched (the use of the * does not work), and one can add additional filters.
Try this:
print(len(list(cursor)))
I always read that people loop through results. Why not using a count(*)?
An example from my production code:
PROCEDURE DeleteStuff___(paras_ IN Parameters_Type_Rec)
IS
CURSOR findEntries_ IS
select * from MyTable
where order_no = paras_.order_no;
counter_ NUMBER;
CURSOR findEntries_count_ IS
SELECT COUNT(*) from MyTable
where order_no = paras_.order_no;
BEGIN
OPEN findEntries_count_;
FETCH findEntries_count_ INTO counter_;
CLOSE findEntries_count_;
dbms_output.put_line('total records found: '||counter_);
IF (counter_ = 0) THEN
-- log and leave procedure
RETURN;
END IF;
FOR order_rec_ IN findEntries_ LOOP
EXIT WHEN findEntries_%NOTFOUND OR findEntries_%NOTFOUND IS NULL;
-- do stuff - i.e. delete a record.
API_Package.Delete(order_rec_);
END LOOP;
END DeleteStuff___;
If the query is small, that is my prefered way.
In this example, I just want to know (and log) how many entries I'll delete.
p.s. Ignore the three underlines. In IFS, this is used when you want private procedures or functions.
You can’t have cursor count at start. For that you need to fetch complete cursor; that is the way get cursor count.
declare
cursor c2 is select * from dept;
var c2%rowtype;
i number :=0;
begin
open c2;
loop
fetch c2 into var;
exit when c2%NOTFOUND;
i: = i+1;
end loop;
close c2;
dbms_output.put_line('total records in cursor'||i);
end;
You can use %ROWCOUNT attribute of a cursor.
e.g:
DECLARE
CURSOR lcCursor IS
SELECT *
FROM DUAL;
BEGIN
OPEN lcCursor ;
DBMS_OUTPUT.PUT_LINE(lcCursor%ROWCOUNT);
CLOSE lcCursor ;
END;

Resources