Better way to tabulate some output data in PL/SQL Oracle?

Hello I'm practicing PL/SQL by doing multiplication tables, I want each multiplication table to look pretty and I used CHR(9) to tab each table, however, it only works perfect when the digits on one table and the next one are the same. It looks bad otherwise as you see in the following picture:

enter image description here

This is the code I'm using:

FOR count1 in multiini..multiend LOOP
    FOR count2 in tablini..tablend LOOP
        DBMS_OUTPUT.PUT(count2||'x'||count1||'='||count2*count1||CHR(9));
    END LOOP;
    dbms_output.new_line;
END LOOP;

Is there a better way to tabulate the output?

Upvotes: 1

Views: 300

Answers (1)

Littlefoot
Littlefoot

Reputation: 142705

How about left padding with spaces, up to maximum result length?

Something like this:

  • max result is produced as multiend * tablend, so the max length is length of each of them + 2 characters for + and = + length of the max result itself + 2 spaces more (to look prettier)
  • use that length as a parameter of the LPAD function

.

declare
  multiini number := 2;
  multiend number := 10;
  tablini number := 3;
  tablend number := 20;
  maxlen number := length(multiend) + length(tablend) + 2 + 
                   length(multiend) * length(tablend) + 2;
begin
  FOR count1 in multiini..multiend LOOP
    FOR count2 in tablini..tablend LOOP
        DBMS_OUTPUT.PUT(lpad(count2||'x'||count1||'='||count2*count1, maxlen, ' '));
    END LOOP;
    dbms_output.new_line;
  END LOOP;
end;
/

Upvotes: 3

Related Questions