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

PL/SQL Exercises

Uploaded by

aliaabfcai25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PL/SQL Exercises

Uploaded by

aliaabfcai25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PL/SQL Exercises

First Example: Transfer Money From Account To Another

‫• أول حاجه محتاج اخصم المبلغ من حساب الشخص اللى بيبعت فلوس‬
‫• تاني حاجه هزود المبلغ اللى خصمته لحساب الشخص اللى ببعتله الفلوس‬

Begin
UPDATE transfer SET balance = balance – :value
WHERE acc_id = :from_acc AND balance >= :value;

UPDATE transfer SET balance = balance + :value


WHERE acc_id = :to_acc;
Transfer
[INSERT INTO transactions
#Acc_ID VALUES(:from_acc, :to_acc, :value, sysdate);] optional
*Name
*Balance End;
oPhone
‫‪Second Example: College System‬‬

‫‪Student‬‬ ‫‪Subject‬‬
‫• المطلوب‪ :‬أول حاجه هحسب مجموع درجات كل مادة عن طريق الحسبة دي ‪:‬‬
‫‪#ID‬‬ ‫‪total = lab + oral + written‬‬
‫‪#Code‬‬
‫‪*Name‬‬
‫‪*Title‬‬
‫‪oScore‬‬
‫‪oDesc‬‬ ‫• تاني حاجه اشوف حالة كل مادة بمعنى الطالب جاب فيها درجة النجاح وال أل‬
‫‪oYear_State‬‬
‫اذن حسب مجموع الدرجات هحدد ‪if total >= 50, then subject state = success‬‬

‫‪Register‬‬ ‫• تالت حاجه هحسب مجموع درجات الطالب (عباره عن مجموع درجات جميع المواد اللى هو‬
‫مسجل فيها)‬
‫‪#Std_ID‬‬
‫‪#Sub_Code‬‬
‫‪oLab‬‬ ‫• رابع حاجه احسب حالة الطالب (راسب أو ناجح) "بالنسبة لجميع المواد" بحسبها عن طريق‪:‬‬
‫‪oWritten‬‬ ‫لو عدد المواد اللى الطالب رسب فيها أكتر من مادتين اذن الطالب بيكون راسب‬
‫‪oOral‬‬
‫‪oTotal‬‬
‫‪oSub_State‬‬
• PL/SQL code:

Begin
-- Register Table
UPDATE register
SET total = nvl(lab,0) + nvl(oral,0) + nvl(written,0) ;
UPDATE register
SET sub_state = ‘S’ WHERE total >= 50 ;
UPDATE register
SET sub_state = ‘F’ WHERE total < 50 ;

-- Student Table
UPDATE student SET score = ( SELECT sum(total) FROM register WHERE register.std_id = student.id );

UPDATE student SET year_score = ‘S’


WHERE (SELECT COUNT(sub_state) FROM register
WHERE sub_state = ‘F’ AND register.std_id = student.id) <= 2;

UPDATE student SET year_score = ‘F’


WHERE (SELECT COUNT(sub_state) FROM register
WHERE sub_state = ‘F’ AND register.std_id = student.id) > 2;

End;
Third Example: Bank Certificate Purchase
Purchase_Cer
#Purchase_serial
#ACC_No
#Cer_type
*Purchase_Date
:pur_seq.nextval
Client Certificate
sysdate
#ACC_No #Cer_Type
*Name *Title
*NID *Period :acc_id
*Balance *Value
:type
Client_Cer
#ACC_No
#Cer_type
*Cer_serial
*Start_Date
*Period
*Value
• PL/SQL Code:
Create sequence pur_sequence
increment by 1
start with 1;
Begin
-- ‫هخصم فلوس الشهادة من حساب المستخدم‬
UPDATE client SET balance = balance – :value
WHERE acc_id = :acc_id AND balance >= :value;

--‫هخزن بيانات العملية فى الداتا بيز‬


INSERT INTO purchase_cer (purchase_serial, acc_no, cer_type, purchase_date)
VALUES(pur_sequence.nextval, :acc_id, :type, sysdate);

commit;

-- Handle run-time error


Exception
dbms_output.put_line(‘Process Failed’);
End;
Schema Object : Sequence
Define a sequence to generate sequential numbers automatically
Schema Object : View ‘Stored Query’
Logically represents subsets of data from one or more table ‘virtual table’
VIEW vs MATERIALIZED VIEW
Feature View (virtual table) Materialized View (physical table)
Storage Does not store data Stores data physically
Data Freshness Always up-to-date May be stale; needs refreshing
Maintenance No refresh needed Requires periodic or on-demand refresh

Refreshing a Materialized View:

• ON DEMAND: Manually refreshed when needed.

• ON COMMIT: Automatically refreshed when a transaction involving the underlying tables is committed.

• Periodic Schedule: Refreshed based on a schedule (e.g., daily, weekly).


Example on Materialized View
The server-side database schema of a Facebook-like application is shown. Users (accounts) can add posts to the
table POSTS.
Each post is described BY POSTID and ACCID as primary key. The client (or mobile) side contains a local database
holds the owner account data MYACCOUNT(ACCID, NAME, ….).
Design an application that retrieves the today’s POSTS from the server-side DB that is published either by the owner
himself or one of his/her friends.

• SQL Code: user


CREATE MATERIALIZED VIEW myposts AS
SELECT accid, postid, postdate, posttext
FROM posts
WHERE postdate = SYSDATE AND
(
posts.accid = :user_id OR
posts.accid IN ( SELECT friendid FROM friendship
WHERE friendship.accid = :user_id)
);
Example on IF statement

• The figure shows three tables: Student, subject and result. The result table
holds the score of subjects for each student. The maximum score for each
subject is 100 degrees. For the student to pass a subject he/she must get 50
degrees or more.
• Design a PL/SQL function called get_state which accepts student ID as a
parameter and returns his state according to the following table:

• State Condition:
‘Failed’ Failed in more than two subjects
‘Pass 2’ If he failed in only 2 subjects
‘Pass 1’ Failed in only 1 subject
‘Success’ If he/she succeeded in all subject
• PL/SQL Code:

Create or replace function get_state (p_std_id student.ID%type) return VARCHR2(10) IS


V_NoFailed Number := 0;
V_STATE VARCHR2(10);
Begin
-- Count number of subjects that the student failed in
SELECT Count(SUB_Code) INTO V_NoFailed FROM RESULT WHERE SCORE <50 and std_id = p_std_id ;

-- Conditional statement
IF V_NoFailed = 0 THEN V_STATE := 'Success' ;
ELSIF V_NoFailed = 1 THEN V_STATE := 'Pass 1' ;
ELSIF V_NoFailed = 2 THEN V_STATE := 'Pass 2' ;
ELSE V_STATE := 'Fail' ;
END IF;

-- Save the new value in the DB


UPDATE student SET state = V_STATE where id = p_std_id ;

return v_state;
END;
Example on Procedure: ‘Login Procedure’

• Write a PLSQL procedure which accepts (login_name, password) and


returns employee name. The procedure validates login employee.
The user table is defined as USER (ID, TrueName, UNAME, PASS).

• PL/SQL Code:

CREATE PROCEDURE Validate (P_ UserName IN User.UName%TYPE ,P_ password IN User.PASS%TYPE,


P_TrueName OUT User.TrueName%TYPE)
User
IS
BEGIN #ID
SELECT TrueName into P_TrueName FROM User *TrueName
WHERE UNAME = P_UserName AND PASS= P_Pass; *UName
*Pass
END;
Example on Procedure: ‘Adding Users’
Write a procedure addUser that takes its date from signup form, user is prompted to enter
his/her :Name, :UserName, :Password. The signup button calls a stored procedure addUser,
which adds a new record to user table. Show how you computes ID as a serial increment.
The USER table is given by USER (ID, TrueName, UNAME, PASS).
CREATE SEQUENCE ID_SEQ -- Create sequence to generate the id
INCREMENT BY 1
START WITH 1
NOCACHE
NOCYCLE;
CREATE OR REPLACE PROCEDURE addUser ( P_TrueName IN User.TrueName%TYPE, P_UNAME IN User.UNAME%TYPE,
P_PASS IN User.PASS%TYPE)
IS
V_ID User.ID%TYPE;
BEGIN
V_ID:= ID_SEQ.NEXTVAL;
INSERT INTO USER (ID, TrueName, UNAME, PASS)
VALUES (V_ID, P_TrueName, P_UNAME, P_PASS);
END;
Calling The Procedure: --In Anonymous block
BEGIN --Code written at submit button
addUser (:Name, :UserName, :Password); -- Passing the ON screen Variables
END;

• Alternative Solution to compute the Serial ID of Users :


CREATE OR REPLACE PROCEDURE addUser ( P_TrueName IN User. TrueName %TYPE, P_UNAME IN User. UNAME
%TYPE, P_PASS IN User . PASS %TYPE)
IS
V_ID User.ID%TYPE;
BEGIN
SELECT NVL(MAX(ID),0) +1 INTO V_ID FROM USER;
INSERT INTO USER (ID, TrueName, UNAME, PASS)
VALUES (V_ID, P_TrueName, P_UNAME, P_PASS);
END;
Example on Function: ‘Login Function’

In a login form, user is prompted to enter his, her :UserName and :Password.
The Login button calls a stored Boolean function Validate, which returns TRUE if
both username and password exist in User Table (ID, TrueName, UNAME, PASS),
else it returns FALSE,
a) Define and write the code of Validate function
b) Show how to call it from login button
c) Modify the code to prevent users from login at ‘Friday’
(a)
CREATE OR REPLACE FUNCTION Validate (P_UserName IN User.UNAME %TYPE , P_Pass IN User.PASS%TYPE) RETURN BOOLEAN
IS
V_UserID User.ID%TYPE;
BEGIN
SELECT ID into V_UserID FROM User WHERE UNAME = P_UserName AND PASS= P_Pass
AND To_CHAR(SYSDATE, ‘Day’) <> ‘Friday’; --prevent users from login at ‘Friday’
IF V_UserID is not null THEN RETURN TRUE;
ELSE RETURN FALSE
END IF;
EXCEPTION
RETURN FALSE;
END;
(b) How to call it
DECLARE
v_login BOOLEAN;
BEGIN
v_login := Validate ( :UserName , :Password); -- call the function
IF v_login = FALSE THEN Message(‘ Not a Valid Login’);
END IF;
END;

You might also like