Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle PL / SQL printing each letter of a string

Tags:

oracle

plsql

I need to print out the letters of the word 'Hello' each on it's own , 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 letter and the out is

l
l
o

any ideas what might be the problem? Thank you.

like image 245
Computerphile Avatar asked May 01 '15 21:05

Computerphile


2 Answers

Better to have Loop end limit For i in 1..v_length This way you do not have to change the Loop limit each time you run.

 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.
like image 105
mahi_0707 Avatar answered Oct 22 '22 06:10

mahi_0707


It can be done in a single select too:

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

L
-
h
e
l
l
o

SQL>
like image 38
Gary_W Avatar answered Oct 22 '22 04:10

Gary_W