Giulio
Giulio

Reputation: 23

increment function in plsql varchar2

I want use this in a varchar2. Ex.:

declare
  num number := &Number;
  serie varchar2(200) := 'S = ';
begin
  for x in 1 .. num loop
    serie += x, ' + ';
  end loop; `
end;
/

In the end I want that the serie be like "S = 1 + 2 + 3 ..." How can i make that work?

Upvotes: 1

Views: 301

Answers (2)

Dmitriy
Dmitriy

Reputation: 5565

What could be done in pure SQL, usually should be done in pure SQL:

declare
  num number := &Number;
  serie varchar2(200);
begin
  select 'S = ' || listagg(rownum, ', ') within group (order by rownum)
    into serie
    from dual
 connect by level <= num;

  dbms_output.put_line(serie);
end;
/

The result for num = 10:

S = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Note, listagg function was introduced in Oracle version 11.2.

Upvotes: 0

Littlefoot
Littlefoot

Reputation: 142720

That would be something like this:

SQL> set serveroutput on
SQL> declare
  2    num number := &Number;
  3    serie varchar2(200) := 'S = ';
  4  begin
  5    for x in 1 .. num loop
  6      serie := serie || to_char(x) || ' + ';
  7    end loop;
  8
  9    -- remove the trailing "+"
 10    serie := rtrim(serie, ' +');
 11    dbms_output.put_Line(serie);
 12  end;
 13  /
Enter value for number: 5
S = 1 + 2 + 3 + 4 + 5

PL/SQL procedure successfully completed.

SQL>

A few comments:

  • line 6: you have to concatenate (concatenation operator is a double pipe sign, ||) previous value of SERIE; otherwise, you'd have only the last number in it
  • line 10: remove the trailing "+" sign

Upvotes: 1

Related Questions