0% found this document useful (0 votes)
20 views3 pages

PL/SQL Salary and Variable Examples

The document contains multiple code examples that demonstrate how to: 1) Retrieve and display an employee's salary using PL/SQL; 2) Declare variables in inner and outer blocks and access them; 3) Use a loop and exception handling to find the first employee above a salary threshold and higher in the management chain; 4) Insert values from a cursor into a table using a for loop.

Uploaded by

Dayit Mitra
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views3 pages

PL/SQL Salary and Variable Examples

The document contains multiple code examples that demonstrate how to: 1) Retrieve and display an employee's salary using PL/SQL; 2) Declare variables in inner and outer blocks and access them; 3) Use a loop and exception handling to find the first employee above a salary threshold and higher in the management chain; 4) Insert values from a cursor into a table using a for loop.

Uploaded by

Dayit Mitra
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Example: The below program will get the salary of an employee with id '1116' and display it on the screen.

DECLARE
 var_salary number(6);
 var_emp_id number(6) = 1116;
BEGIN
 SELECT salary
 INTO var_salary
 FROM employee
 WHERE emp_id = var_emp_id;
 dbms_output.put_line(var_salary);
 dbms_output.put_line('The employee '
|| var_emp_id || ' has salary ' || var_salary);
END;
/
Example: In the below example we are creating two variables in the outer block and assigning thier product to the third variable created in
the inner block. The variable 'var_mult' is declared in the inner block, so cannot be accessed in the outer block i.e. it cannot be accessed
after line 11. The variables 'var_num1' and 'var_num2' can be accessed anywhere in the block.
1> DECLARE
2> var_num1 number;
3>  var_num2 number;
4> BEGIN
5>  var_num1 := 100;
6>  var_num2 := 200;
7>  DECLARE
8>   var_mult number;
9>   BEGIN
10>    var_mult := var_num1 *
var_num2;
11>   END;
12> END;
13> /

In the following example, you find the first employee who has a salary over $2500 and is higher in
the chain of command than employee 7499:
DECLARE
salary [Link]%TYPE := 0;
mgr_num [Link]%TYPE;
last_name [Link]%TYPE;
starting_empno [Link]%TYPE := 7499;
BEGIN
SELECT mgr INTO mgr_num FROM emp
WHERE empno = starting_empno;
WHILE salary <= 2500 LOOP
SELECT sal, mgr, ename INTO salary, mgr_num, last_name
FROM emp WHERE empno = mgr_num;
END LOOP;
INSERT INTO temp VALUES (NULL, salary, last_name);
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO temp VALUES (NULL, NULL, 'Not found');
COMMIT;
END;

DECLARE
x NUMBER := 100;
BEGIN
FOR i IN 1..10 LOOP
IF MOD(i,2) = 0 THEN -- i is even
INSERT INTO temp VALUES (i, x, 'i is even');
ELSE
INSERT INTO temp VALUES (i, x, 'i is odd');
END IF;
x := x + 100;
END LOOP;
COMMIT;
END;

SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;

ENAME EMPNO SAL


---------- --------- --------
KING 7839 5000
SCOTT 7788 3000
FORD 7902 3000
JONES 7566 2975
BLAKE 7698 2850
CLARK 7782 2450
ALLEN 7499 1600
TURNER 7844 1500
MILLER 7934 1300
WARD 7521 1250
MARTIN 7654 1250
ADAMS 7876 1100
JAMES 7900 950
SMITH 7369 800

PL/SQL Block
-- available online in file 'sample2'
DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC; -- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal NUMBER(7,2);
BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total */
/* number of employees */
INSERT INTO temp VALUES (my_sal, my_empno, my_ename);
COMMIT;
END LOOP;
CLOSE c1;
END;

Output Table
SQL> SELECT * FROM temp ORDER BY col1 DESC;

NUM_COL1 NUM_COL2 CHAR_COL


-------- -------- --------
5000 7839 KING
3000 7902 FORD
3000 7788 SCOTT
2975 7566 JONES
2850 7698 BLAKE

Common questions

Powered by AI

Predefined types such as 'emp.sal%TYPE' and 'emp.empno%TYPE' inherit data types directly from existing database columns, ensuring consistency and reducing type mismatch errors. Their use is important because it aligns program variable types with the corresponding table column types, promoting compatibility and maintenance ease . This mechanism automates data type adjustments if the database schema changes, simplifying updates and preventing potential runtime errors.

Exception handling in a PL/SQL loop is crucial for managing errors that occur during database operations, such as fetching records. In the example provided, the exception 'NO_DATA_FOUND' is handled to safely insert a 'Not found' entry into the 'temp' table, ensuring the program's flow is not abruptly interrupted when no data is retrieved . This prevents indefinite loops and allows for graceful handling of unexpected situations.

Modular design in PL/SQL enhances program maintenance and scalability by organizing code into smaller, self-contained blocks that can be independently developed and debugged. This results in cleaner code, easier updates, and reuse of components. For instance, declaring separate variables for each computational block confines any changes to those specific areas, reducing the risk of unintended effects on other parts of the program . This promotes scalable development practices by allowing additional features to be added with minimal disruption to existing functionality.

Using a cursor in PL/SQL allows efficient handling of multi-row query results by fetching rows one at a time, which can improve resource management and performance. Cursors reduce the load on network and database resources by allowing data processing to happen in manageable chunks. In the example, a cursor is opened and fetched iteratively within a loop, which prevents memory overload by not holding all result rows at once . This approach ensures efficient use of memory and reduces the application's footprint on the server.

A PL/SQL FOR loop enhances control by automatically managing loop iteration, reducing the risk of off-by-one errors and reducing the need for explicit loop control initialization, condition checking, and incrementation. It creates a concise way to iterate over a range, such as 'FOR i IN 1..10', which will execute for each integer value within the specified range . This avoids the manual setup and potential errors associated with traditional while or basic loops, leading to more readable and maintainable code.

In PL/SQL, the block structure determines the scope and accessibility of variables. Variables declared in an inner block are not accessible from outer blocks. For example, in the nested block example, 'var_mult' is declared inside the inner block and cannot be accessed beyond line 11, which belongs to the outer block . However, variables declared in the outer block, like 'var_num1' and 'var_num2,' can be accessed anywhere within the outer block .

The logic involves an iterative process using a WHILE loop to traverse the management hierarchy until an employee with a salary above the specified amount ($2500) is found . Data integrity is maintained using a robust exception handling mechanism. If NO_DATA_FOUND is triggered when no manager exists in the dataset, the program inserts a 'Not found' entry into the 'temp' table and commits the transaction, avoiding incomplete data entries .

Inserting NULL values into a table during exception handling in PL/SQL implies that the operation faced an issue, like absence of intended data, which the program has explicitly recognized and managed . This approach ensures that the database accurately reflects the absence of data rather than interrupting program execution unexpectedly. However, it may require additional processing logic to handle these NULL values during further operations, maintaining data integrity and providing a clear error context.

The '%NOTFOUND' attribute in PL/SQL is used to determine whether the last FETCH statement was successful. When processing a cursor, '%NOTFOUND' becomes true if no more rows are available, which typically exits a loop to prevent attempts to process non-existent data. In the example, '%NOTFOUND' is checked in each iteration to exit the loop when all employees have been processed .

The condition 'IF MOD(i,2) = 0' is used to determine if an integer 'i' is even. The MOD function returns the remainder of division, so a result of 0 indicates evenness. This condition is part of a loop to insert values into a table where the odd/even status of 'i' affects the stored information. Specifically, it checks through values 1 to 10, alternating between inserting 'i is even' or 'i is odd' text along with 'i' and an accumulator 'x' .

You might also like