Open In App

Swap two numbers in PL/SQL

Last Updated : 17 May, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements.
In declare part, we declare variables and between begin and end part, we perform the operations.

Basic structure of pl/sql block

declare
-- declare all the variables

begin  -- for start block
-- make a program here

end -- for end block

You have given two numbers num1 and num2 the your task is to swap the value of given numbers.

Examples:

Input : num1  = 1000 num2 = 2000
Output : num1  = 2000 num2 = 1000

Input : num1  = 40 num2 = 20
Output : num1  = 20 num2 = 40




declare
  
-- declare variable num1, num2 
-- and temp of datatype number
    num1 number;
    num2 number;
    temp number;
  
   
begin
    num1:=1000;
    num2:=2000;
      
    -- print result before swapping
    dbms_output.put_line('before');
    dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);
      
    -- swapping of numbers num1 and num2
    temp := num1;
    num1 := num2;
    num2 := temp;
      
   -- print result after swapping
    dbms_output.put_line('after');
    dbms_output.put_line('num1 = '|| num1 ||' num2 = '|| num2);
      
end;


Output:

before
num1  = 1000 num2 = 2000
after
num1  = 2000 num2 = 1000

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads