Rdbms Recordwork
Rdbms Recordwork
                               SQL INTRODUCTION
   1     DDL COMMANDS
2 DML&TCL COMMANDS
3 INTEGRITY CONSTRAINTS
4 SQL OPERATORS
5 SQL FUNCTIONS
8 SUBQUERIES
9 DCL COMMANDS
10 OTHER DB OBJECTS
PL/SQL
13 TRIGGERS
14 EXCEPTION HANDLING
  15     SUB PROGRAMS
  16     PACKAGES
 Ex. No.1                              DDL STATEMENTS                  Date:
  Example: create table student (regno number (11), name varchar2 (25), addr varchar2(25),
           dept varchar2 (3));
  Output:
           Table created.
  Example:
  I.  alter table student modify (name varchar2 (30));
      Output:
               Table altered.
  II.   alter table student add (comments long);
        Output:
                 Table altered.
4. DESC COMMAND
   ● This command will display the structure of the table.
   Syntax:   Desc <table name>;
   Output:
             Name                                Null? Type
             ---------------------------------- -------- ----------------------------
             REGNO                                        NUMBER(11)
             NAME                                         VARCHAR2(30)
             DEPT                                          VARCHAR2(3)
             COMMENTS                                      LONG
   Output:
             Table dropped.
EMP
                 Column Name            DataType            Description
                 ENO                    Number              Employee Number
                 ENAME                  Varchar             Emp Name
                 JOB                    Char                Designation
                 MGR                    Number              Manager EMPno
                 HIREDATE               Date                Date of Joining
                 SAL                    Number              Basic Salary
                 COMM                   Number              Commission
                 DEPTNO                 Number              Department Number
Table created.
Table created.
SQL>desc dept
Q4. Modify the size of the column LOC by 15 in the DEPT table.
Table altered.
Table altered.
Table altered.
Table renamed.
Table dropped.
1. INSERT COMMAND
  ● Used to add one or more rows to a table.
  ● While using this command the values are separated by commas and the data types char
    and date are enclosed in apostrophes.
  ● The values must be entered in the same order as they are defined in the table.
  Syntax:
  ● To insert all column values for each row
    SQL> Insert into <table_name> values (a list of data values);
  ● To insert specific column values for each row
    SQL> Insert into <table_name> (col_names) values (list of values);
2. SELECT COMMAND
  ● Used to perform a query. The query is a request for information.
  Syntax: Select column_name … from table_name … where conditions [order by
          column_name …];
     ● To select only specific columns, specify the column names instead of * in the select
       command.
3. UPDATE COMMAND
  ● Used to alter the column values in a table.
  ● Specific rows could be updated based on a specific condition.
  Syntax: Update table_name set field = value, … where condition;
  ● The ‘where’ clause and the ‘set’ clause can also include queries.
4. DELETE COMMAND
  ● Used to delete one or more rows to a table.
  Syntax: Delete from <table_name> where conditions;
Q3. Create a table MANAGER with the columns mgr-id, name, salary and hiredate
SQL> create table mgr(mgr_id number(5) primary key,name varchar(25),sal number(5),hiredate date);
Table created.
Q4. Insert values into manager table by copying values from emp table where the
designation is ‘MANAGER’.
SQL> insert into mgr select mgr,ename,sal,hiredate from empl where job='manager';
1 row created.
Q5. Change the Loc of all the rows of DEPT table by ‘New York’.
Q10. Without duplication, list all the names of the department in DEPT table.
SQL> select distinct ename from empl;
ENAME
-------------------------
jones
smith
Q11. Find out the name of the employee whose empno is 7369.
SQL> select ename from empl where empno=7369;
ENAME
----------
smith
Q12. As a copy of DEPT table, create DEPT1 table using select command.
Table Created
Q13. List ename and sal of EMP table with the column headings NAME and SALARY
         NAME                         SALARY
         ------------------------- ----------
         smith                       800
         jones                      2975
Q14. Change LOC=’CHICAGO’ for deptno=30 in DEPT table and COMMIT the
transaction.
         SQL>savepoint update_over;
      c) Insert another row in DEPT table with your own values
       An integrity constraint is a mechanism used by Oracle to prevent invalid data entry into
   the table, by enforcing rule for the column in a table.
Q1.Add not null constraint to the columns ename and job of emp table.
SQL>alter table empl modify(ename varchar2(25) not null, job char(30) not null);
Table Altered
Q2. Add Primary key constraint to the column empno of emp table.
SQL>alter table empl add constraint emp_pk primary key(empno);
Table Altered
Q3. Add Primary key constraint to the column dno of dept table.
SQL> SQL>alter table dept add constraint dept_pk primary key(deptno);
Table Altered
Q4.Add unique constraint to the column dname of dept table.
SQL> alter table dept add constraint chk unique(deptno);
Table altered.
Q5.Add check constraints to the table EMP to restrict the values of empno lies between
7000 and 8000.
SQL>Alter table empl add constraint emp_ck check(empno between 7000 and 8000)
Table Alterd
Q6. Add Foreign key constraint to the column deptno of emp table references deptno of
dept table.
SQL>alter table emp add constraint emp_fk foreign key(deptno) references dept(deptno);
Table altered.
Q7. Remove the primary key constraint on the DEPT table and drop the associated foreign
key constraint on emp.deptno column.
SQL>alter table dept drop primary key cascade;
Table altered
Q8. Disable the primary key constraint of the EMP table.
SQL>alter table empl disable constraint emp_pk cascade;
Table alterd
Q9. View all the user constraint definitions and its names.
SQL>select * from user_constraints where table_name=’emp’;
  Ex. No.4                               SQL OPERATORS               Date:
Arithmetic Operators
       +Addition
       -Subtraction
       *Multiplication
       /Division
Comparison Operators
       =Equal to
       <>Not Equal to
       <Less than
       >Greater than
       <=Less than or equal to
       >=Greater than or equal to
       IN (List)Match any of list of values
       LIKEMatch a character pattern (% any no. of characters, -
       IS NULLIs a null value
       BETWEEN…AND…Between two values
Logical Operators
       ANDReturns TRUE if both component conditions are TRUE
       ORReturns TRUE if either component condition is TRUE
       NOTReturns TRUE if the following condition is FALSE
Concatenation Operator ( || )
        Concatenates the Columns of any data type.
        A Resultant column will be a Single column.
Order by Clause
 Sort rows specified by the order ASC / DESC
 SELECTcolumn1, column2, … …
 FROM table
 ORDER BY sort-column DESC;
 Sorts table by sort-column in descending order
 Omitting the keyword DESC will sort the table in ascending order
Q1. Update all the records of Manager table by increasing 10% of their salary as bonus.
1 row updated.
Q2. Delete the records from Manager table whose salary less than 2750.
1 rows deleted.
Q3.List concatenated values of name and designation of each employee.
ENAME||JOB
----------------------------------------
smithclerk
jonesmanager
ENAME
-------------------------
Smith
ENAME
-------------------------
smith
JOB
---------------
clerk
manager
salesman
Q9.List the names of employees who joined between 30Jun81 AND 31Dec81.
SQL> select ename from empl where hiredate between '30-JUN-81' and '31-DEC-81';
no rows selected
Q10. List the names of employees who are not eligible for commission.
EMPNO ENAME
---------- -------------------------
7369        smith
7566        jones
Q11.List the employees whose name either starts or ends with ‘s’.
SQL> select ename from empl where ename like 's%' or ename like '%s';
ENAME
-------------------------
smith
jones
ENAME
-------------------------
Miller
Q13. Sort the emp table in ascending order by hiredate and display the details.
Q14. Sort the emp table in descending order of the annual salary.
  I.        ADD_MONTHS –Returns a data after adding a specified date with the specified
            number of months.
         Output:
                ADD_MONTH
                ------------------
                07-APR-08
II. LAST_DAY – Returns the date corresponding to the last day of the month.
         Output:
                SYSDATE LAST_DAY
                ------------- --------------
                07-FEB-08 29-FEB-08
                           Output:
                                   ROUND (TO_
                                   ------------------
                                   01-MAR-08
                        3) select round (to_date ('07-Feb-08', 'dd-Mon-yy'), 'day') from dual;
                           Output:
                                   ROUND (TO_
                                   ------------------
                                   10-FEB-08
                        4) select round (to_date ('07-Feb-08', 'dd-Mon-yy')) from dual;
                            Output:
                                   ROUND (TO_
                                   ------------------
                                   07-FEB-08
     VI.                      TRUNCATE          – Returns the date with the time portion of the day
                              truncated to the unit specified by format model.
                  GREATEST
                  -----------------
                  10-JUL-08
2. CHARACTER FUNCTIONS
Ltrim (char, set) select ltrim (‘xyzadams’, ‘xyz’) from dual; adams
Rtrim (char, set) select rtrim (‘xyzadams’, ‘ams’) from dual; xyzad
Translate (char, from, to) select translate (‘jack’, ‘j’, ‘b’) from dual; back
 Replace               (char,         select replace (‘jack and jue’, ‘j’, ‘bl’) from
                                                                                        black and blue
 searchstring, [rep string])          dual;
I. SOUNDEX – Returns words that are spelled differently, but sound alike.
Example: select to_char (sysdate, 'ddth "of" Month yyyy') from dual;
         Output:
                TO_CHAR (SYSDATE,'DDTH"
                ----------------------------------------
                09th of February 2008
   II.   TO_DATE
         Output:
                TO_DATE ('
                ----------------
                15-JAN-08
5. MISCELLANEOUS FUNCTIONS
I. UID – Returns the integer value corresponding to the user currently logged in.
         Output:
                   UID
              ----------
                    62
   II.   USER – Returns the login’s user name, which is in varchar2 data type.
         Output:
                USER
                ------------------------------
                PRINCE
III.   NVL
Output:
              NVL(ROLLNO,0)            NAME
              ----------------------   ------------------------------
                       1               Raja
                       2               Prince
                       3               Raja
                       0               James
IV.             VSIZE – Returns        the number of bytes in the expression. If expression is null,
                it returns null.
Output:
              VSIZE ('HELLO')
              ----------------------
                        5
   Ex. No.6                          SQL GROUP FUNCTIONS                  Date:
Group functions Operate on sets of rows to give one result per group
Syntax:
                 Select column,groupfunction(column)
                 From table
                 [Where condition]
                 [Group by expression]
                 [Having group condition]
                 [Order by column name]
Q1. Find the number of rows in table EMP?
SQL>select count(*) from emp;
COUNT(*)
---------
       6
Q2.Find the number of designations available in emp?
SQL> SQL> select count(distinct job) from empl;
COUNT(DISTINCTJOB)
-----------------------------
             2
Q3.Find the number of employees who earn commission in emp table?
SQL> select count(*) from empl where comm<>0 or comm<>null;
COUNT(*)
----------
      4
Q4. Find total salary paid to employees.
SQL> select sum(sal) from empl;
SUM(SAL)
-------------
    3775
Q5.Find maximum, minimum and average salary of the Employees?
SQL> select max(sal),min(sal),avg(sal) from emp;
MAX(SAL) MIN(SAL) AVG(SAL)
------------     ---------- ----------
9000         6000       7725
Q6.Find the number of employees who work in deptno 20.
SQL> select count(empno) from empl where deptno=20;
COUNT(EMPNO)
------------
        2
Q7. Find the max salary paid to a clerk?
SQL> select max(sal) from empl where job='clerk';
MAX(SAL)
----------
     800
Q8.List the department numbers and no of employees in each department.
SQL> select deptno,count(empno) from empl group by deptno;
DEPTNO COUNT(EMPNO)
---------- ------------
      10            5
      20            2
Q9. List the jobs and number of employees in each job. The result should be in the
descending order of the number of employees.
Q10. List the total salary, maximum and minimum salary and average salary of the
employees jobwise, for department 20 and display only those rows having an
average salary > 1000.
Q11. List the job and total salary of employees jobwise, for jobs other than
‘PRESIDENT’ and display only those rows having total salary > 5000.
JOB       SUM(SAL)
--------- ------------
ANALYST          6000
MANAGER           8275
SALESMAN          5600
Q12. List the job, number of employees and average salary of employees jobwise.
Display only the rows where the number of employees in each job is more than
two.
Set Operations
      Combines the results of two queries into a single one.
                     Operator                        Function
                   Union        Returns all distinct rows selected by either
                                query
                   Union all    Returns all distinct rows selected by either
                                query including duplicates
                   Intersect    Returns only rows that are common to both the
                                queries
                   Minus        Returns all rows selected only by the first
                                query but not by the second.
Q2.List the names of distinct customers who have either loan or account
SQL> select distinct(cus_name) from depositor union select distinct(cus_name) from borrower;
CUS_NAME
-------------------------
Jones
paul
smith
Q3. List the names of customers (with duplicates) who have either loan or account
SQL> select cus_name from depositor union all select cus_name from borrower;
CUS_NAME
-------------------------
Jones
smith
paul
smith
paul
Q4.List the names of customers who have both loan and account
SQL> select cus_name from depositor intersect select cus_name from borrower;
CUS_NAME
-------------------------
paul
smith
Q5.List the names of customers who have loan but not account
SQL> select cus_name from depositor minus select cus_name from borrower;
CUS_NAME
-------------------------
Jones
Joins:
         They are used to combine the data spread across the tables.A JOIN Basically involves
more than one Table to interact with.Where clause specifies the JOIN Condition.
Ambiguous Column names are identified by the Table name.
         If join condition is omitted, then a Cartesian product is formed. That is all rows in
the first table are joined to all rows in the second table
Types of Joins
  Inner Join (Simple Join)              : Retrieves rows from 2 tables having common columns.
    o Equi Join                         : A join condition with =.
    o Non Equi Join                     :A join condition other than =
  Self Join                             : Joining table to itself.
  Outer Join                            : Returns all the rows returned by simple join as well as
                                         those rows from one table that do not match any row from
                                         another table
Q1. List empno, ename, deptno from emp and dept tables.
SQL> select e.empno,e.ename,e.deptno
       from emp e,dept d
       where e.deptno=d.deptno;
40 rows selected.
Q3. List the names of the employee with name of his/her manager from emp table.
13 rows selected.
   Ex. No.8                                      SUB QUERIES             Date:
The subquery (inner query) executes once before the main query.The result of the subquery is
used by the main query (outer query).
Q1. List the name of the employees whose salary is greater than that of employee with
empno 7566.
SQL> SELECT ENAME FROM EMPWHERE SAL >(SELECT SAL FROM EMP WHERE
EMPNO=7566);
ENAME
-------------------------
FORD
Q2. List the name of the employees whose job is equal to the job of employee with
empno 7499 and salary is greater than that of employee with empno 7521.
SQL> SELECT ENAME FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE
EMPNO=7499) and SAL>(SELECT SAL FROM EMP WHERE EMPNO=7521);
ENAME
-------------------------
ALLEN
Q3. List the ename,job,sal of the employee who get minimum salary in the company.
SQL> select ename,job,sal from empl where sal=(select min(sal) from empl);
Q4. List deptno & min(salary) departmentwise, only if min(sal) is greater than the
min(sal) of deptno 20.
   DEPTNO MIN(SAL)
---------- ----------
      30       1250
Q5. List empno, ename, job of the employees whose job is not a ‘CLERK’ and whose
salary is less than at least one of the salaries of the employees whose job is
‘CLERK’.
SQL>select empno,ename,job from emp where sal < any(select sal from emp where
job='CLERK') and job <>'CLERK';
Q6.List empno, ename, job of the employees whose salary is greater than the average
salary of each department.
SQL>select empno,ename,job from emp where sal > all(select avg(sal) from emp group by
deptno);
Q7. List ename, job, sal of the employees whose salary is equal to any one of the
  salary of the employee ‘SCOTT’ or ‘WARD’.
SQL> select ename,job,sal from emp where sal =any(select sal from emp where ename='SCOTT'
or ename='WARD');
Q8. List ename, job, sal of the employees whose salary and job is equal to theemployee
‘FORD’.
SQL> select ename,job,sal from emp where job=(select job from emp where ename='FORD')
and sal=(select sal from emp where ename='FORD');
1. CREATING USERS
2. GRANT PRIVILEGE COMMAND – Used to grant database object’s privileges [i.e. right
   to access another user’s objects (table, view, …)] to other users.
   Syntax: Grant privileges on <object-name> to <username>;
3. REVOKE PRIVILEGE COMMAND – Used to withdraw the privilege which has been
   granted to a user.
   Syntax: Revoke privileges on <object-name> from <username>;
Q5. Grant privileges to update the columns dname & loc of dept table to the user scott
Q6. Grant insert and select privileges on dept table to the user scott with the authority
topass along the privileges.
Q7. As user Alice, revoke the select and insert privileges given to user scott on the
dept table.
. I.   VIEWS
       An Imaginary table contains no data and the tables upon which a view is based
       are called base tables.
       Logically represents subsets of data from one or more tables
Advantages of view
   To restrict database access
   To make complex queries easy
   To allow data independence
   To present different views of the same data
SYNTAX:
Q1. Create a view empv10 that contains empno, ename, job,sal of the employees who
work in dept 10. Also describe the structure of the view.
View Created
Q3. Update the view empv10 by increasing 10% salary of the employees who work as
‘CLERK’. Also confirm the modifications in emp table.
SYNTAX:
Cycle          - continues to generate values after reaching either its max or min
               value. The default is ‘nocycle’
Cache          -Oracle pre allocates sequence numbers and keep the in memory
for faster access. The default is ‘nocache’.
Pseudo columns
Q1. Create a sequence dept_seq to be used for the primary key of dept table.
Q3. Insert a new department named ‘MARKETING’ in San Diego using the sequence
dept_seq.
PROGRAM
Declare
    a number;
    b number;
    c number;
Begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('Sum of ' || a || ' and ' || b || ' is ' || c);
End;
/
OUTPUT
PROGRAM
Declare
    a number;
    b number;
    c number;
Begin
    a:=&a;
    b:=&b;
    c:=&c;
    if (a>b) and (a>c) then
          dbms_output.put_line('A is Maximum');
    elsif (b>a) and (b>c) then
          dbms_output.put_line('B is Maximum');
    else
          dbms_output.put_line('C is Maximum');
    end if;
End;
/
OUTPUT
SQL> /
Enter value for a: 4
old 6:      a:=&a;
new 6:       a:=4;
Enter value for b: 3
old 7:      b:=&b;
new 7:       b:=3;
Enter value for c: 5
old 8:      c:=&c;
new 8:       c:=5;
C is Maximum
Declare
    a number;
    s1 number default 0;
Begin
    a:=1;
    loop
        s1:=s1+a;
        exit when (a>100);
        a:=a+2;
    end loop;
    dbms_output.put_line('Sum of odd numbers from 1 to 100 is '||s1);
End;
/
OUTPUT
OUTPUT
SQL> /
Enter value for no: 34
old 2:       no number (3) := &no;
new 2:        no number (3) := 34;
34 is not a prime number
    declare
     salary number(5);
   begin
     select sal into salary from emp where empno=7369;
if salary < 2500 then
     update emp set sal=sal+sal*25/100 where empno=7369;
     elsif salary between 2500 and 5000 then
     update emp set sal=sal+sal*20/100 where empno=7369;
     else
     update emp set sal=sal+comm where empno=7369;
   end if;
  end;
SQL> /
OUTPUT
Q6. Write a PL/SQL Block to list ename, sal & deptno all information about the
    employee whose empno is given as input.
PROGRAM
     1 declare
     2 emp_rec emp%rowtype;
     3 n number;
     4 begin
     5 n:=&n;
     6 select * into emp_rec from emp where empno=n;
      7    dbms_output.put_line('Ename: '||emp_rec.ename||'       Salary:   '||emp_rec.sal||'
    Deptno: ' ||emp_rec.deptno);
     8* end;
OUTPUT
    SQL> /
    Enter value for n: 7369
    old 5:      n:=&n;
    new 5:       n:=7369;
    Ename: smith Salary: 1000              Deptno: 20
Q7. Write a PL/SQL Block to find the number of employees (say n) in emp table and
Print the numbers1 to 10 in descending order.
PROGRAM
        1 declare
        2 n number;
        3 i number;
        4 begin
       5 select count(*) into n from emp ;
        6 dbms_output.put_line('No of employees : ' || n);
        7 dbms_output.put_line('Printing numbers 1..10 in descending order');
        8 for i in reverse 1..10
        9 loop
        10        dbms_output.put_line(i);
        11 end loop;
        12* end;
OUTPUT
No of employees : 10
Printing numbers 1..10 in descending order
10
9
8
7
6
5
4
3
2
1
Cursor
        A cursor is a temporary work area created in the system memory when a SQL
statement is executed. A cursor contains information on a select statement and the
rows of data accessed by it. This temporary work area is used to store the data
retrieved from the database, and manipulate this data. A cursor can hold more
than one row, but can process only one row at a time. The set of rows the cursor
holds is called the active set.
Q1. Write a PL/SQL Block, to update salaries of all the employees who work in
deptno 20 by 15%. If none of the employee’s salary are updated display a
message 'None of the salaries were updated'. Otherwise display the total number
of employee who got salary updated.
PROGRAM
 Declare
num number(5);
 Begin
update emp set sal = sal + sal*0.15 where deptno=20;
if SQL%NOTFOUND then
dbms_output.put_line('none of the salaries were updated');
elsif SQL%FOUND then
num := SQL%ROWCOUNT;
dbms_output.put_line('salaries for ' || num || 'employees are updated');
  end if;
 End;
OUTPUT
SQL> /
salaries for 5employees are updated
PL/SQL procedure successfully completed.
Q2. Write a PL/SQL block to find the name and salary of first five highly paid
employees.
PROGRAM
 1 declare
 2 emp_rec emp%rowtype;
 3 cursor c is select * from emp order by sal desc;
 4 begin
 5 open c;
 6 dbms_output.put_line('Highest paid first 5 employees');
 7 loop
 8      fetch c into emp_rec;
 9      dbms_output.put_line(emp_rec.ename||'       ' ||emp_rec.sal);
10 exit when c%rowcount=5;
11 end loop;
12* end;
SQL> /
FORD       3450
SCOTT      3450
jones      3421.25
BLAKE      2850
ALLEN      1600
       A trigger is a PL/SQL block structure which is fired when DML statements like
Insert,Delete and Update is executed on a database table. A trigger is triggered
automaticallywhen an associated DML statement is executed.
SYNTAX
     CREATE [OR REPLACE ] TRIGGER trigger_name
     {BEFORE | AFTER | INSTEAD OF }
     {INSERT [OR] | UPDATE [OR] | DELETE}
     [OF col_name]
     ON table_name
     [REFERENCING OLD AS o NEW AS n]
     [FOR EACH ROW]
     WHEN (condition)
BEGIN
      -- SQL Statements
END;
Q1. Create a trigger which will not allow you to enter duplicate or null values in
column empno of emp table.
PROGRAM
Q2. Create a database trigger that allows changes to employee table only during the
 business hours(i.e. from 8 a.m to 5 p.m.) from Monday to Friday. There is no
restriction on viewing data from the table
PROGRAM
Trigger created.
1 row deleted.
        Exceptions can beinternally defined (by the runtime system) or user-defined. Examples of
internallydefined exceptions include division by zero and out of memory.
        When an error occurs, an exception is raised. That is, normal execution stops and control
transfers to the exception handling part of your PL/SQL block or subprogram. Internal
exceptions are raised implicitly (automatically) by the runtime system. User-defined exceptions
must be raised explicitly by RAISE statements, which can also raise predefined exceptions.
Syntax
EXCEPTION
  WHEN ... THEN
      - handle the error differently
  WHEN ... OR ... THEN
      - handle the error differently
  ...
  WHEN OTHERS THEN
      - handle the error differently
END;
PROGRAM
Declare
  n1 number;
 n2 number;
Begin
n2 := &n2;
Select sal into n1 from empl where empno=7654;
n1 := n1/n2;
Exception
       when zero_divide then
           dbms_output.put_line('Zero Divide Error !');
       when no_data_found then
           dbms_output.put_line('No such Row in EMP table');
       when others then
           dbms_output.put_line('Unknown exception');
end;
OUTPUT
SQL> /
Enter value for n2: 2
Old 5: n2 := &n2;
New 5: n2 := 2;
PL/SQL procedure successfully completed.
SQL> /
Enter value for n2: 0
Old 5: n2 := &n2;
New 5: n2 := 0;
Zero Divide Error !
PL/SQL procedure successfully completed.
Q2. Write PL/SQL block to raise ‘out-of-balance’ exception if balance fall below 100.
PROGRAM
DECLARE
     out_of_balance EXCEPTION;
     bal NUMBER:=&bal;
BEGIN
     IF bal < 100 THEN
RAISE out_of_balance;
     END IF;
  EXCEPTION
         WHEN out_of_balance THEN
         dbms_output.put_line('Low balance. Unable to do Transactions');
END;
OUTPUT
SQL> /
Enter value for bal: 50
old 3:     bal NUMBER:=&bal;
new 3:     bal NUMBER:=50;
Low balance. Unable to do Transactions
PL/SQL procedure successfully completed.
 Ex. No.15                              SUB PROGRAMS                    Date:
Subprograms are named PL/SQL blocks that can take parameters and be invoked.
PL/SQL has two types of subprograms called procedures and functions. Generally, we
use a procedure to perform an action and a function to compute a value.
I. PROCEDURES
Syntax :
PROGRAM
Declare
       a number;
       b number;
       c number;
       procedure findmin(x in number,y in number,z out number) is
       begin
              if x < y then
              z:=x;
              else
              x:=y;
              end if;
       end;
begin
         a:=&a;
         b:=&b;
         findmin(a,b,c);
         dbms_output.put_line(‘Minimum is ‘ || c);
end;
/
OUTPUT
Enter value for a: 34
Enter value for b: 12
Minimum is 12
PL/SQL procedure successfully completed.
Q2. Write a standalone PL/SQL procedure to check for palindrome.
      Create or replace procedure palin(str in varchar(20),revstr out varchar(20) ) as
      c number;
      begin
              c:=length(str);
              while (c>0) loop
              revstr:=revstr || substr(str,c,1);
              c:=c-1;
              end loop;
      end;
/
OUTPUT:
SQL> /
Procedure created.
Execute the procedure from another program
Declare
              str varchar(20);
              rev varchar(20);
begin
              str:=’&str’;
              palin(str,rev);
              if (str=rev) then
              dbms_output.put_line(‘It is a palindrome’);
              else
              dbms_output.put_line(‘It is not a palindrome’);
              end if;
end;
II. FUNCTIONS
        A function is a subprogram that computes a value. Functions and procedure are structured
alike, except that functions have a RETURN clause.
Syntax :
     FUNCTION name [ (parameter, [, parameter, ...]) ] RETURN datatype IS
          [local declarations]
     BEGIN
          executable statements
          [EXCEPTION
                exception-handlers]
     END [name];
PROGRAM
OUTPUT:
SQL> /
Function created.
Function Calling Program
 declare
   n number;
   f number;
 begin
    n:=&n;
    f:=fact(n);
   dbms_output.put_line('Factorial of ' || n || ' is '||f);
 end;
OUTPUT
SQL> /
Enter value for n: 8
old 5:       n:=&n;
new 5:         n:=8;
Factorial of 8 is 40320
Packages
       A package is a database object that groups logically related PL/SQL types, objects, and
subprograms. Packages usually have two parts, a specification and a body,
.
Syntax
PACKAGE name IS -- specification (visible part)
   -- public type and object declarations
   -- subprogram specifications
END [name};
PACKAGE BODY name IS -- body (hidden part)
   -- private type and object declarations
   -- subprogram bodies
   [BEGIN
        -- initialization statements]
END [name];
Q1. Create a package with a procedure to retrieve the salary of the employee taking empno
as input.
                                  Creating Package Specification
SQL> Create package p as
             Procedure find_sal(no emp eno%type);
      End p;
             /
Package created.
                                     Creating Package Body:
SQL> create or replace package body p as
             Procedure find_sal(no emp eno%type)
             Sal emp.salary%type;
             Begin
                 Select salary into sal from emp where eno=no;
                 Dbms_output.put_line(‘Salary of the employee is ‘ || sal);
             End;
             /
Package body created.
                                   Calling the Package:
SQL> declare
             Id emp.eno%type;
             Begin
               Id:=&id;
               p.find_sal(id);
end;
/
OUTPUT:
             Enter Id: 7326
             Salary of the employee is 5000
Q2. Create a package to pack a record, a cursor and two employment procedures.
PROGRAM
SQL> CREATE PACKAGE emp_actions AS-- specification
        TYPE EmpRecTyp is RECORD (eno INTEGER, salary REAL);
        CURSOR desc_salary (eno NUMBER) RETURN EmpRecTyp;
        PROCEDURE hire_employee
           (ename CHAR, job CHAR, mgr NUMBER, sal NUMBER,
        comm NUMBER, deptno NUMBER );
        PROCEDURE fire_employee (eno NUMBER);
    END emp_actions;
    /
Package created.