This is one of the most basic and common programs for beginners to write. It teaches you the fundamental structure of a PL/SQL program, including how to declare variables, assign values, perform a calculation, and print the result.
This simple guide will walk you through the process step-by-step.
What You Need to Know
To write this program, you will use a few basic PL/SQL concepts:
- Enabling Output: Before you can see any printed results, you must run this command once in your SQL tool (like SQL*Plus or SQL Developer):
SET SERVEROUTPUT ON; - Anonymous Block: We will write our code in a
DECLARE...BEGIN...END;block. This is the standard way to run a simple PL/SQL script. - Variables: We need to
DECLAREvariables to hold our two numbers (e.g.,n1andn2) and a third variable to store the sum (e.g.,sum_result). All will be of theNUMBERdata type. - Assignment Operator (
:=): In PL/SQL, you use:=(a colon followed by an equals sign) to assign a value to a variable. - Printing the Result: We use
DBMS_OUTPUT.PUT_LINE()to print the final answer to the screen.
PL/SQL Program: Add Two Numbers
This program adds two hardcoded numbers (n1 and n2) and prints their sum.
PL/SQL Program
SET SERVEROUTPUT ON;
DECLARE
-- Define our two numbers
n1 NUMBER := 15;
n2 NUMBER := 30;
-- A variable to hold the sum
sum_result NUMBER;
BEGIN
-- Perform the addition
sum_result := n1 + n2;
-- Print the final result to the screen
DBMS_OUTPUT.PUT_LINE('The sum of ' || n1 || ' and ' || n2 || ' is: ' || sum_result);
END;
/
Result
The sum of 15 and 30 is: 45
Program Explanation
DECLAREsection: We create three variables.n1andn2are given initial values of15and30.sum_resultis declared but has no value yet (it isNULL).BEGINsection: This is where the program's logic starts.sum_result := n1 + n2;: This is the core logic. It calculates15 + 30, gets the result45, and assigns that value to oursum_resultvariable.DBMS_OUTPUT.PUT_LINE(...): The program prints a single string to the screen. It uses the||(concatenation) operator to join the text strings with the values from our variables.END;and/: This signals the end of the PL/SQL block and tells the SQL tool to execute it.
