p9.21
p9.21
Aim: PL/SQL block for loop, arithmetic operations, function and procedure
1. Write a PL/SQL program to illustrates the use of varrays.
SOURCE CODE:
DECLARE
BEGIN
END LOOP;
END;
/
OUTPUT :
SOURCE CODE:
CHOSALIYA MIT
230280116021
DECLARE
num NUMBER := 5; -- The number for which factorial is calculated
factorial NUMBER := 1; -- Variable to store the factorial result
BEGIN
-- Calculate factorial using a FOR loop
FOR i IN 1..num LOOP
factorial := factorial * i;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is: ' ||
factorial); END;
/
OUTPUT:
3. Write a PL/SQL program to create a simple procedure that displays the string 'Hello World!' on the screen when
executed
SOURCE CODE :
CHOSALIYA MIT
230280116021
DECLARE
-- Declare the procedure
PROCEDURE display_hello_world IS
BEGIN
BEGIN
-- Call the procedure display_hello_world;
END;
/
OUTPUT :
4. Write a PL/SQL program that makes the use of cursor to display CUSTOMER data in the customers table.
SOURCE CODE :
CHOSALIYA MIT
230280116021
DECLARE
customers.customer_id%TYPE;
v_customer_name
customers.customer_name%TYPE; v_customer_email
customers.customer_email%TYPE;
END LOOP;
-- Close the cursor
CLOSE customer_cursor;
END;
/
CHOSALIYA MIT
230280116021
OUTPUT :
5. Write a PL/SQL function that returns the total number of CUSTOMERS in the customers table.
SOURCE CODE :
CHOSALIYA MIT
230280116021
v_total_customers NUMBER;
BEGIN
-- Query to get the total number of customers
SELECT COUNT(*) INTO v_total_customers FROM customers;
-- Return the total number of customers
RETURN v_total_customers;
END get_total_customers;
/
DECLARE
total_customers NUMBER;
BEGIN
-- Call the function total_customers := get_total_customers;
OUTPUT :
6. Write a PL/SQL Function that computes and returns the maximum of two values.
SOURCE CODE :
CHOSALIYA MIT
230280116021
NUMBER;
BEGIN
:= a;
ELSE v_maximum_value
:= b;
END IF;
RETURN v_maximum_value;
END get_maximum_value;
DECLARE
result NUMBER;
BEGIN
OUTPUT :
7. Write a PL/SQL program to calculates the factorial of a given number by calling itself recursively
SOURCE CODE :
RETURN 1;
ELSE
-- Recursive case: n! = n * (n-1)!
RETURN n * calculate_factorial(n - 1);
END IF;
END calculate_factorial;
/
DECLARE
num NUMBER := 5; -- Change this to the desired number result
NUMBER;
BEGIN
-- Call the function to calculate factorial result
:= calculate_factorial(num);
OUTPUT :