SQL Tutorial
SQL Clauses / Operators
SQL-Injection
SQL Functions
SQL Queries
PL/SQL
MySQL
SQL Server
Misc
To compute the sum of the digits of a number in PL/SQL, you can use a loop that repeatedly divides the number by 10, adds the remainder to the sum, and then truncates the last digit. Here's how you can do that:
DECLARE n NUMBER := 12345; -- example number sum_digits NUMBER := 0; remainder NUMBER; BEGIN WHILE n > 0 LOOP remainder := MOD(n, 10); -- get the last digit sum_digits := sum_digits + remainder; -- add the last digit to the sum n := TRUNC(n / 10); -- remove the last digit END LOOP; DBMS_OUTPUT.PUT_LINE('Sum of digits: ' || sum_digits); END; /
In this example, the sum of the digits of the number 12345
will be computed, and 15
will be displayed as the result. You can replace 12345
with any other number to compute the sum of its digits.
PL/SQL Program to Calculate Sum of Digits of a Number:
DECLARE num INTEGER := 12345; digit_sum INTEGER := 0; temp_num INTEGER := num; BEGIN WHILE temp_num > 0 LOOP digit_sum := digit_sum + MOD(temp_num, 10); temp_num := temp_num / 10; END LOOP; DBMS_OUTPUT.PUT_LINE('Sum of digits: ' || digit_sum); END; /
Oracle SQL Function for Finding Sum of Digits:
CREATE OR REPLACE FUNCTION calculate_digit_sum ( num IN INTEGER ) RETURN INTEGER IS digit_sum INTEGER := 0; temp_num INTEGER := num; BEGIN WHILE temp_num > 0 LOOP digit_sum := digit_sum + MOD(temp_num, 10); temp_num := temp_num / 10; END LOOP; RETURN digit_sum; END calculate_digit_sum; /
PL/SQL Procedure for Digit Summation:
CREATE OR REPLACE PROCEDURE calculate_digit_sum_proc ( num IN INTEGER ) IS digit_sum INTEGER := 0; temp_num INTEGER := num; BEGIN WHILE temp_num > 0 LOOP digit_sum := digit_sum + MOD(temp_num, 10); temp_num := temp_num / 10; END LOOP; DBMS_OUTPUT.PUT_LINE('Sum of digits: ' || digit_sum); END calculate_digit_sum_proc; /
Oracle SQL Query to Find Sum of Digits in a Number:
SELECT num, calculate_digit_sum(num) AS digit_sum FROM your_table;
Sum of Individual Digits in a Number in PL/SQL:
DECLARE num INTEGER := 9876; temp_num INTEGER := num; BEGIN WHILE temp_num > 0 LOOP DBMS_OUTPUT.PUT_LINE('Digit: ' || MOD(temp_num, 10)); temp_num := temp_num / 10; END LOOP; END; /
Oracle SQL Program to Find Digit Sum:
SELECT num, SUM(MOD(num, 10)) AS digit_sum FROM your_table GROUP BY num;