Oracle PL / SQL prints every letter of a string

I need to print the letters of the word "Hello" each one, I wrote this:

Declare
c1 Number:=1;
c2 Varchar2(5);
begin
for c1 in 1..5
loop
select substr('Hello' , c1 , 1 ) into c2 from dual;
dbms_output.put_line(c2);
end loop;
end;

      

but it skips the first two letters and out

l
l
o

      

any ideas what the problem might be? Thank.

+3


source to share


4 answers


Better to have an end-of-loop constraint For i in 1..v_length

This way you don't have to change the constraint Loop

every time you start.



 Create or replace procedure print_string( IN_string IN varchar2 )
AS
v_length number(10);
v_out varchar2(20);
Begin
v_length := length(IN_string);
for i in 1..v_length
Loop
v_out  := substr(IN_string,i,1) ;
DBMS_OUTPUT.PUT_LINE(v_out);
End loop;
DBMS_OUTPUT.PUT_LINE('Text printed: ' || IN_string);
End;
 -- Procedure created.

BEGIN
print_string('Hello');
END;


-- Output:

H
e
l
l
o
Text printed: Hello

Statement processed.

      

+3


source


This can be done in one choice too:



SQL> select substr('hello', level, 1) Letter
  2  from dual
  3  connect by level <= length('hello');

L
-
h
e
l
l
o

SQL>

      

+2


source


The script icon you wrote is right.

Declare
c1 Number:=1;
c2 Varchar2(5);
begin
for c1 in 1..5
loop
select substr('Hello' , c1 , 1 ) into c2 from dual;
dbms_output.put_line(c2);
end LOOP;
end;

      

Output: -

H
e
l
l
o

      

+1


source


Your script:

declare
    c1 number := 1;
    c2 varchar2(5);
begin
    for c1 in 1 .. 5 loop
        select substr('Hello', c1, 1) into c2 from dual;
        dbms_output.put_line(c2);
    end loop;
end;

      

Outputs the following:

H
e
l
l
o

      

Everything looks good to me.

What result are you getting?

0


source







All Articles