Sql – PL/SQL how to write multiple statement in a single stored procedure

oracleplsqlsql

I need to do the following problem,

Write a procedure that decreases the salary by a 10% for all employees who earn
less than the current average salary.
Treat the content of table EMP as “all employees”. Have your procedure print the name and salary of the first
person whose salary is just below the average.

What should be the approach to solve the problem?

Write a procedure that decreases the salary by a 10% for all employees who earn less than the current average salary.

CREATE OR REPLACE PROCEDURE UPDATE_EMP IS
BEGIN
UPDATE EMP
SET SAL= SAL-(SAL*0.1) 
WHERE SAL<(SELECT AVG(SAL) FROM EMP);
END;

AND THE OTHER ONE :
Have your procedure print the name and salary of the first person whose salary is just below the average.

SELECT e.ename
     , e.sal
 from 
    (select ename
            , sal 
      from emp 
      where sal < (select avg(sal)  
                     from emp
                   ) 
     order by sal desc 
     )e  
  where ROWNUM =1;

Now I need to connect both.. How could I do that …

Best Solution

It sounds like you are a bit fuzzy on what a stored procedure is and how it can help you do complicated tasks involving many SQL statements.

You follow these directions on how a construct a stored procedure.

http://www.devshed.com/c/a/Oracle/Oracle-Stored-Procedures/

Stored procedures are wonderful structures that allow you to put multiple SQL statements into one structure, saving out variables for use in the next SQL statement. So all you have to do is invoke the stored procedure, and all the sql statements are run, and your answer is returned or table modification is committed.

You need something like this:

CREATE OR REPLACE PROCEDURE UPDATE_EMP RETURN name, value IS
BEGIN

    UPDATE EMP
    SET SAL= SAL-(SAL*0.1) 
    WHERE SAL<(SELECT AVG(SAL) FROM EMP);

    SELECT e.ename INTO name_to_return, e.sal INTO sal_to_return from 
    (select ename, sal from emp where sal < (select 
     avg(sal)from emp) order by sal desc)e   where ROWNUM =1;

    RETURN name_to_return, sal_to_return;
END;

The syntax may be a bit off, when you get it working, post your answer here as a new answer, and check mark it as the answer, and you are much more likely to get help like this in the future.