Find the total salary of employees without using the sum function.
To find the sum salary of all employees we use basically Oracle SUM() Function. suppose in interviews the interviewer asks to find the sum salary without using the SUM function!
we achieve it by using LOOPS.
--------------------------------------
Example -1
SET SERVEROUTPUT ON;
DECLARE
TOTAL_SAL NUMBER:=0;
BEGIN
FOR I IN (SELECT SAL FROM EMP)
LOOP
TOTAL_SAL:=TOTAL_SAL+I.SAL;
END LOOP;
DBMS_OUTPUT.PUT_LINE(TOTAL_SAL);
END;
Output-
46475
PL/SQL procedure successfully completed.
Method 2 Using Cursor for loop-
----------------------------------------
DECLARE
total_salary NUMBER := 0;
CURSOR c_emp_salary IS
SELECT sal
FROM emp;
BEGIN
FOR emp_rec IN c_emp_salary LOOP
total_salary := total_salary + emp_rec.sal;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total Salary: ' || total_salary);
END;
Output-
Total Salary: 46475
PL/SQL procedure successfully completed.
0 Comments