PL/SQL Program To Add Two Numbers

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:

  1. 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;
  2. 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.
  3. Variables: We need to DECLARE variables to hold our two numbers (e.g., n1 and n2) and a third variable to store the sum (e.g., sum_result). All will be of the NUMBER data type.
  4. Assignment Operator (:=): In PL/SQL, you use := (a colon followed by an equals sign) to assign a value to a variable.
  5. 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

  1. DECLARE section: We create three variables. n1 and n2 are given initial values of 15 and 30. sum_result is declared but has no value yet (it is NULL).
  2. BEGIN section: This is where the program's logic starts.
  3. sum_result := n1 + n2;: This is the core logic. It calculates 15 + 30, gets the result 45, and assigns that value to our sum_result variable.
  4. 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.
  5. END; and /: This signals the end of the PL/SQL block and tells the SQL tool to execute it.
Vinish Kapoor
Vinish Kapoor

Vinish Kapoor is a seasoned software development professional and a fervent enthusiast of artificial intelligence (AI). His impressive career spans over 25+ years, marked by a relentless pursuit of innovation and excellence in the field of information technology. As an Oracle ACE, Vinish has distinguished himself as a leading expert in Oracle technologies, a title awarded to individuals who have demonstrated their deep commitment, leadership, and expertise in the Oracle community.

guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments