Swapping the values of two variables (making a become b and b become a) is one of the most fundamental logic puzzles in programming. In PL/SQL, this is easily accomplished by using a third, temporary variable.
This simple guide will show you the logic and a complete program to solve this problem.
What You Need to Know
To write this program, you will use a few basic PL/SQL concepts:
- Enabling Output: You must run this command once in your SQL tool to see the printed results:
SET SERVEROUTPUT ON; - Anonymous Block: We will write our code in a
DECLARE...BEGIN...END;block. - Variables: We'll need three variables:
n1(our first number),n2(our second number), andv_temp(a temporary variable to help with the swap). - The "Swap Logic": To swap two numbers, you can't just do
n1 := n2andn2 := n1. This would fail because the original value ofn1would be lost. The correct way is:- Copy
n1intov_temp. - Copy
n2inton1. - Copy
v_tempinton2.
- Copy
- Printing the Result: We use
DBMS_OUTPUT.PUT_LINE()to show the values before and after the swap.
PL/SQL Program: Swap Two Numbers
This program will take two numbers, n1 and n2, swap their values, and print the results to the screen.
PL/SQL Program
SET SERVEROUTPUT ON;
DECLARE
-- Define our two numbers
n1 NUMBER := 10;
n2 NUMBER := 20;
-- A temporary variable to hold a value during the swap
v_temp NUMBER;
BEGIN
-- 1. Print the values *before* the swap
DBMS_OUTPUT.PUT_LINE('--- Before Swap ---');
DBMS_OUTPUT.PUT_LINE('n1: ' || n1);
DBMS_OUTPUT.PUT_LINE('n2: ' || n2);
-- 2. Perform the 3-step swap logic
v_temp := n1; -- v_temp is now 10
n1 := n2; -- n1 is now 20
n2 := v_temp; -- n2 is now 10 (from v_temp)
-- 3. Print the values *after* the swap
DBMS_OUTPUT.PUT_LINE('--- After Swap ---');
DBMS_OUTPUT.PUT_LINE('n1: ' || n1);
DBMS_OUTPUT.PUT_LINE('n2: ' || n2);
END;
/
Result
--- Before Swap ---
n1: 10
n2: 20
--- After Swap ---
n1: 20
n2: 10
Program Explanation
DECLAREsection: We createn1(value 10),n2(value 20), andv_temp(no value, orNULL).BEGINsection: The program's logic starts.DBMS_OUTPUT.PUT_LINE(...): First, we print the starting values ofn1(10) andn2(20).v_temp := n1;: This is the first step of the swap. We copy the value ofn1(10) intov_temp.n1= 10,n2= 20,v_temp= 10
n1 := n2;: This is the second step. We copy the value ofn2(20) inton1. The original value ofn1is now gone, but that's okay because we saved it inv_temp.n1= 20,n2= 20,v_temp= 10
n2 := v_temp;: This is the final step. We copy the value fromv_temp(10) inton2.n1= 20,n2= 10,v_temp= 10
DBMS_OUTPUT.PUT_LINE(...): Now that the swap is complete, we print the final values ofn1(now 20) andn2(now 10).
