0% found this document useful (0 votes)
491 views

PL Lab Manual-1

Pl lab
Copyright
© © All Rights Reserved
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)
491 views

PL Lab Manual-1

Pl lab
Copyright
© © All Rights Reserved
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
You are on page 1/ 20

VAAGDEVI COLLEGE OF ENGINEERING

(AUTONOMOUS)
DATABASE PROGRAMMING WITH PL/SQL LAB (Lab - II )
Professional Elective - I

M.Tech CSE I Year I Sem. L T P C


0 0 4 2

• Course Objectives:

• 1. Knowledge on significance of SQL fundamentals.

• 2. Evaluate functions and triggers of PL/SQL .

• 3. Knowledge on control structures, packages in PL/SQL and its applications .

• Course Outcomes:

• 1. Understand importance of PL/SQL basics

• 2. Implement functions and procedures using PL/SQL

• 3. Understand the importance of triggers in database.

ListofPrograms

Week 1 : Write a pl/sql program using FOR LOOP to insert ten rows into a database table.

Week 2.Give the table EMPLOYEE (EmpNo,Name,Salary,Designation ,DeptID),write a


cursor to select the three highest paid employees from the table.

Week 3.IILUSTRATE how you can embed PL/SQL in a high level HOST language SUCH AS
C/JAVA AND DEMONSTRATE BANKING DEBIT CARD TRANSACTION might be done.

Week 4.GIVEN AN INTEGER i,write a PL/SQL procedure to insert the tuple (i,'XXX')into a given
relation.

Week 5.Write PL/SQL Program to demonstrate Exceptions.

Week 6.Write PL/SQL queries to demonstrate Cursor.

Week 7.Write PL/SQL Program to demonstrate Functions.

Week 8.Write PL/SQL program to demonstrate Packages.

Week 9.Write PL/SQL queries to create Procedures.

Week 10.Write PL/SQL queries to create Triggers.


INDEX

S.No. Week Experiment PageNo.


1 Week-1 Write a pl/sql program using FOR LOOP to insert ten
rows into a database table

2 Week-2 Give the table EMPLOYEE


(EmpNo,Name,Salary,Designation ,DeptID
),write a cursor to select the three highest
paid employees from the table.

3 Week-3 IILUSTRATE how you can embed PL/SQL in a high


level HOST language SUCH AS C/JAVA AND
DEMONSTRATE BANKING DEBIT CARD
TRANSACTION might be done.

4 Week-4 GIVEN AN INTEGER i,write a PL/SQL procedure to


insert the tuple (i,'XXX')into a given relation.

5 Week-5 Write PL/SQL Program to demonstrate Exceptions


6 Week-6 Write PL/SQL queries to demonstrate Cursor.

7 Week-7 Write PL/SQL Program to demonstrate Functions.

8 Week-8 Write PL/SQL program to demonstrate Packages

9 Week-9 Write PL/SQL queries to create Procedures


10 Week-10 Write PL/SQL queries to create Triggers.
1. Week1. Write a pl/sql program using FOR LOOP to insert ten rows into a database
table.
1. BEGIN
2. FOR k IN 1..10 LOOP
3. -- note that k was not declared
4.DBMS_OUTPUT.PUT_LINE(k);
5. END LOOP;
6.END;

OUTPUT:

11
1
2
2.Give the table EMPLOYEE (EmpNo,Name,Salary,Designation ,DeptID),write
a cursor to select the three highest paid employees from the table.

createtable employee(
emp_no integerprimary key
,lastname varchar2(20) notnull
,salary number(3)
);

insertinto employee(emp_no,lastname,salary)
values(1,'Tomy',2);

insertinto employee(emp_no,lastname,salary)
values(2,'Jacky',3);

insertinto employee(emp_no,lastname,salary)
values(3,'Joey',4);

insertinto employee(emp_no,lastname,salary)
values(4,'Janey',5);

select lastname, salary


from (SELECT lastname, salary FROM employee ORDERBY salary DESC)
where rownum <=3 ;

OUTPUT :

LASTNAME SALARY
------------------- ----------------------
Janey 5
Joey 4
Jacky 3
3.IILUSTRATE how you can embed PL/SQL in a high level HOST language SUCH AS
C/JAVA AND DEMONSTRATE BANKING DEBIT CARD TRANSACTION might be
done.

/* available online in file 'sample5' */


#include <stdio.h>
char buf[20];
EXEC SQL BEGIN DECLARE SECTION;
int acct;
double debit;
double new_bal;
VARCHAR status[65];
VARCHAR uid[20];
VARCHAR pwd[20];
EXEC SQL END DECLARE SECTION;

EXEC SQL INCLUDE SQLCA;

main()
{
extern double atof();

strcpy (uid.arr,"scott");
uid.len=strlen(uid.arr);
strcpy (pwd.arr,"tiger");
pwd.len=strlen(pwd.arr);

printf("\n\n\tEmbedded PL/SQL Debit Transaction Demo\n\n");


printf("Trying to connect...");
EXEC SQL WHENEVER SQLERROR GOTO errprint;
EXEC SQL CONNECT :uid IDENTIFIED BY :pwd;
printf(" connected.\n");
for (;;) /* Loop infinitely */
{
printf("\n** Debit which account number? (-1 to end) ");
gets(buf);
acct = atoi(buf);
if (acct == -1) /* Need to disconnect from Oracle */
{ /* and exit loop if account is -1 */
EXEC SQL COMMIT RELEASE;
exit(0);
}

printf(" What is the debit amount? ");


gets(buf);
debit = atof(buf);

/* ---------------------------------- */
/* ----- Begin the PL/SQL block ----- */
/* ---------------------------------- */
EXEC SQL EXECUTE

DECLARE
insufficient_funds EXCEPTION;
old_bal NUMBER;
min_bal CONSTANT NUMBER := 500;
BEGIN
SELECT bal INTO old_bal FROM accounts
WHERE account_id = :acct;
-- If the account doesn't exist, the NO_DATA_FOUND
-- exception will be automatically raised.
:new_bal := old_bal - :debit;
IF :new_bal >= min_bal THEN
UPDATE accounts SET bal = :new_bal
WHERE account_id = :acct;
INSERT INTO journal
VALUES (:acct, 'Debit', :debit, SYSDATE);
:status := 'Transaction completed.';
ELSE
RAISE insufficient_funds;
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
:status := 'Account not found.';
:new_bal := -1;
WHEN insufficient_funds THEN
:status := 'Insufficient funds.';
:new_bal := old_bal;
WHEN OTHERS THEN
ROLLBACK;
:status := 'Error: ' || SQLERRM(SQLCODE);
:new_bal := -1;
END;

END-EXEC;
/* -------------------------------- */
/* ----- End the PL/SQL block ----- */
/* -------------------------------- */

status.arr[status.len] = '\0'; /* null-terminate */


/* the string */
printf("\n\n Status: %s\n", status.arr);
if (new_bal >= 0)
printf(" Balance is now: $%.2f\n", new_bal);
} /* End of loop */

errprint:
EXEC SQL WHENEVER SQLERROR CONTINUE;
printf("\n\n>>>>> Error during execution:\n");
printf("%s\n",sqlca.sqlerrm.sqlerrmc);
EXEC SQL ROLLBACK RELEASE;
exit(1)}
Interactive Session
Embedded PL/SQL Debit Transaction Demo

Trying to connect... connected.

** Debit which account number? (-1 to end) 1


What is the debit amount? 300

Status: Transaction completed.


Balance is now: $700.00

** Debit which account number? (-1 to end) 1


What is the debit amount? 900
Status: Insufficient funds.
Balance is now: $700.00

** Debit which account number? (-1 to end) 2


What is the debit amount? 500

Status: Transaction completed.


Balance is now: $1500.00

** Debit which account number? (-1 to end) 2


What is the debit amount? 100

Status: Transaction completed.


Balance is now: $1400.00

** Debit which account number? (-1 to end) 99


What is the debit amount? 100

Status: Account not found.

** Debit which account number? (-1 to end) -1


Output Tables:
SQL> SELECT * FROM accounts ORDER BY account_id;

ACCOUNT_ID BAL
---------- ------
1 700
2 1400
3 1500
4 6500
5 500

SQL> SELECT * FROM journal ORDER BY date_tag;

ACCOUNT_ID ACTION AMOUNT DATE_TAG


-------------- -------------------- --------- ----------------
1 Debit 300 28-NOV-88
2 Debit 500 28-NOV-88
2 Debit 100 28-NOV-88
4. GIVEN AN INTEGER i,write a PL/SQL procedure to insert the tuple (i,'XXX')into a given relation.

CREATE TABLE T1(


e INTEGER,
f INTEGER
);

DELETE FROM T1;


INSERT INTO T1 VALUES(1, 3);
INSERT INTO T1 VALUES(2, 4);

/* above is plain SQL; below is the PL/SQL statement */

DECLARE
a NUMBER;
b NUMBER;
BEGIN
SELECT e,f INTO a,b FROM T1 WHERE e>1;
INSERT INTO T1 VALUES(b,a);
END;
.
OUTPUT:
Fortuitously, there is only one tuple of T1 that has first component greater than 1, namely
(2,4). The insert-statement thus inserts (4,2) into T1.
5.Write PL/SQL Program to demonstrate Exceptions.

DECLARE

salary_too_high EXCEPTION;

current_salary NUMBER := 20000;

max_salary NUMBER := 10000;

erroneous_salary NUMBER;

BEGIN

BEGIN

IF current_salary > max_salary THEN

RAISE salary_too_high; -- raise exception

END IF;

EXCEPTION

WHEN salary_too_high THEN -- start handling exception

erroneous_salary := current_salary;

DBMS_OUTPUT.PUT_LINE('Salary ' || erroneous_salary ||' is out of range.');

DBMS_OUTPUT.PUT_LINE ('Maximum salary is ' || max_salary || '.');

RAISE; -- reraise current exception (exception name is optional)

END;

EXCEPTION

WHEN salary_too_high THEN -- finish handling exception

current_salary := max_salary;

DBMS_OUTPUT.PUT_LINE (

'Revising salary from ' || erroneous_salary ||

' to ' || current_salary || '.'


);

END;

OUTPUT :

Salary 20000 is out of range.

Maximum salary is 10000.

Revising salary from 20000 to 10000.


6.Write PL/SQL queries to demonstrate Cursor.

1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12. END;
13. /

Output:

6 customers updated.
PL/SQL procedure successfully completed.
7.Write PL/SQL Program to demonstrate Functions.
DECLARE

x INTEGER;

FUNCTION f (n INTEGER)

RETURN INTEGER

IS

BEGIN

RETURN (n*n);

END;

BEGIN

DBMS_OUTPUT.PUT_LINE (

'f returns ' || f(2) || '. Execution returns here (1).'

);

x := f(2);

DBMS_OUTPUT.PUT_LINE('Execution returns here (2).');

END;

OUTPUT :

f returns 4. Execution returns here (1).Execution returns here (2).


8.Write PL/SQL program to demonstrate Packages.

CREATE OR REPLACE PACKAGE aa_pkg AUTHID DEFINER IS

TYPE aa_type IS TABLE OF INTEGER INDEX BY VARCHAR2(15);

END;

CREATE OR REPLACE PROCEDURE print_aa (

aa aa_pkg.aa_type

) AUTHID DEFINER IS

i VARCHAR2(15);

BEGIN

i := aa.FIRST;

WHILE i IS NOT NULL LOOP

DBMS_OUTPUT.PUT_LINE (aa(i) || ' ' || i);

i := aa.NEXT(i);

END LOOP;

END;

DECLARE

aa_var aa_pkg.aa_type;

BEGIN

aa_var('zero') := 0;

aa_var('one') := 1;

aa_var('two') := 2;

print_aa(aa_var);

END;
/

OUTPUT :

1 one

2 two

0 zero

9.Write PL/SQL queries to create Procedures.


DECLARE

first_name employees.first_name%TYPE;

last_name employees.last_name%TYPE;

email employees.email%TYPE;

employer VARCHAR2(8) := 'AcmeCorp';

-- Declare and define procedure

PROCEDURE create_email ( -- Subprogram heading begins

name1 VARCHAR2,

name2 VARCHAR2,

company VARCHAR2

) -- Subprogram heading ends

IS

-- Declarative part begins

error_message VARCHAR2(30) := 'Email address is too long.';

BEGIN -- Executable part begins

email := name1 || '.' || name2 || '@' || company;

EXCEPTION -- Exception-handling part begins

WHEN VALUE_ERROR THEN

DBMS_OUTPUT.PUT_LINE(error_message);

END create_email;

BEGIN

first_name := 'John';

last_name := 'Doe';

create_email(first_name, last_name, employer); -- invocation


DBMS_OUTPUT.PUT_LINE ('With first name first, email is: ' || email);

create_email(last_name, first_name, employer); -- invocation

DBMS_OUTPUT.PUT_LINE ('With last name first, email is: ' || email);

first_name := 'Elizabeth';

last_name := 'MacDonald';

create_email(first_name, last_name, employer); -- invocation

END;

OUTPUT:

With first name first, email is: John.Doe@AcmeCorp

With last name first, email is: Doe.John@AcmeCorp

Email address is too long.

10.Write PL/SQL queries to create Triggers.

1. CREATE OR REPLACE TRIGGER display_salary_changes


2. BEFORE DELETE OR INSERT OR UPDATE ON customers
3. FOR EACH ROW
4. WHEN (NEW.ID > 0)
5. DECLARE
6. sal_diff number;
7. BEGIN
8. sal_diff := :NEW.salary - :OLD.salary;
9. dbms_output.put_line('Old salary: ' || :OLD.salary);
10. dbms_output.put_line('New salary: ' || :NEW.salary);
11. dbms_output.put_line('Salary difference: ' || sal_diff);
12. END;
13. /

OUTPUT:

Trigger created.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy