PL/SQL - String concatenation algorithm - oracle

I'm working on a PL/SQL algorithm, with Oracle.
I currently have a procedure which have one single numeric parameter. My procedure have to create a string which contains as much '0' as the parameter value.
I am currently using a for loop to achieve this:
MY_STRING VARCHAR2(30);
FOR I IN 1..MY_PARAMETER
LOOP
MY_STRING := CONCAT(MY_STRING, '0');
END LOOP;
Is it possible to do it in a linear way ? I mean without a loop, or even with one single statement.
Any help would be appreciated !
Thanks.

You can use LPAD() to achieve this:
SELECT LPAD('0', my_parameter, '0')
FROM DUAL
Here is the link to the manual:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions082.htm#i1371196

Demonstration of accepted answer using various input values.
set serveroutput on size 1000000 format wrapped
Declare
my_parameter Number(3);
my_string Varchar2(10);
Begin
DBMS_Output.Put_Line('Input Output');
DBMS_Output.Put_Line('===== ======');
For vLoopVar IN 0..5 Loop
my_parameter := vLoopVar;
If (vLoopVar = 5) Then
my_parameter := '';
End If;
DBMS_Output.Put(RPAD('~' || my_parameter || '~',6));
--Method 1
my_string := lpad('0',my_parameter,'0');
DBMS_Output.Put_Line('~' || my_string || '~');
End Loop;
End;
/
Output
Input Output
===== ======
~0~ ~~
~1~ ~0~
~2~ ~00~
~3~ ~000~
~4~ ~0000~
~~ ~~

Related

How to modify a CLOB line containing a certain value by using a trigger with PLSQL?

I am struggling with an issue regarding a CLOB.
I would like to create a trigger (after update) which updates the column of a table which is a CLOB.
This CLOB contains lines in this form :
foo|132|65|12/08/2016|18395|
bar|132|54|15/08/2014|32434343|
I would like to modify the CLOB such that the line beginning with "foo" has the value "18395" divided by 1000. The line will look like
foo|132|65|12/08/2016|18.395|
Is there a quick way to modify my CLOB?
Thank you for your help.
EDIT : I found a way to modify the line of the CLOB what I need to do is just to modify the CLOB to replace
foo|132|65|12/08/2016|18395|
by
foo|132|65|12/08/2016|18.395|
This is rather long but effective.
Firstly create a type:
create or replace TYPE "array_str" AS VARRAY(10) OF VARCHAR(256);
Then create a function that will return a array based in a delimiter:
FUNCTION string_to_array (
string_delimited IN VARCHAR2,
delimiter IN VARCHAR2 DEFAULT ','
) RETURN array_str IS
pls_idx PLS_INTEGER;
split_string array_str := array_str();
pls_del_len PLS_INTEGER := length(delimiter);
BEGIN
IF string_delimited IS NOT NULL THEN
LOOP
-- search for delimiter string
pls_idx := instr(l_string_delimited, delimiter);
-- increase the size of array
split_string.extend;
-- check last search of delimiter is success
IF pls_idx = 0 THEN
split_string(l_split_string.count) := substr(l_string_delimited, 1);
ELSE
split_string(l_split_string.count) := substr(l_string_delimited, 1, pls_idx - 1);
END IF;
-- exit from loop when last string
EXIT WHEN nvl(l_pls_idx, 0) = 0;
string_delimited := substr(l_string_delimited, pls_idx + pls_del_len);
END LOOP;
END IF;
RETURN split_string;
END string_to_array;
Then create your trigger:
CREATE OR REPLACE TRIGGER your_trigger AFTER
UPDATE ON table_name
FOR EACH ROW
DECLARE
clob_array array_str;
clob_str CLOB := '';
BEGIN
clob_array := string_to_array(:new.new_clob, '|');
IF ( clob_array(1) = 'foo' ) THEN
clob_array(5) := to_number(clob_array(5) / 1000);
END IF;
FOR i IN 1..clob_array.count - 1 LOOP clob_str := clob_str
|| to_char(clob_array(i))
|| '|';
END LOOP;
-- do something with clob_str
END;

How to built a dynamic string PLSQL

I have 2 associative_arrays of number and I am trying to built a dynamic string for a dynamic query.
This is my for statement:
for indx_opt in 1..IDOPTarray.count loop
IF indx_opt=1 AND IDFGCFCParray.count=1 THEN
sql_stmt_2:=sql_stmt_2||' and wopt.id_ft_opt = ';
sql_stmt_2:=sql_stmt_2|| (IDOPTarray(indx_opt));
end if;
if indx_opt=1 AND IDFGCFCParray.count>1 then
sql_stmt_2:=sql_stmt_2||' and wopt.id_ft_opt in(';
sql_stmt_2:=sql_stmt_2||(IDOPTarray(indx_opt));
elsif indx_opt>=1 AND IDFGCFCParray.count>=0 then
sql_stmt_2:=sql_stmt_2||','||(IDOPTarray(indx_opt))||')';
With 2 number in IDOPTarray I get a correct result:
and wopt.id_ft_opt in(27,28)
Instead with more then 2 number in IDOPTarray I get this result:
,17228),17229),17230)
What I want to get is this:
where w.id = 303 and wopt.id_ft_opt in (17228,17229,17230)
if I have 5 numbers, I want to get this for the 'where' clause:
where w.id = 321 and wopt.id_ft_opt in (17228,17229,17230,17231,17232)
I want a dynamic output of my string.
IDFGCFCParray is the 2nd array, but is not important right now in order to get the output I want.
Does somebody can help me? thank you.
You have to close bracket only if indx_opt is equil to IDOPTarray.count.
And simple example.
declare
type list_number is table of number;
xx list_number := new list_number(1,2,3,5,7,8);
str varchar2(4000);
begin
for i in xx.first .. xx.last loop
if i = 1 then
str := ' condition in ('||xx(i);
else
str := str||','||xx(i);
end if;
if i = xx.last then
str := str||')';
end if;
end loop;
dbms_output.put_line(str);
end;
If you colleciton is sql levle type you can do this in this way
declare
xx list_number := new list_number(1,2,3,5,7,8);
str varchar2(4000);
begin
SELECT 'condition in ('||LISTAGG(column_value, ',') WITHIN GROUP (ORDER BY column_value)||')' into str from table(xx);
dbms_output.put_line(str);
end;

loop counter case in oracle procedure

Is there any loop counter in procedure.
How to handle below case.
BEGIN
FOR recAnnLang IN getLang(var_non_subscribe)
LOOP
// if loop 1 recAnnLangCode.Ann_Lang assign to var1
var1 := recAnnLangCode.Ann_Lang;
// if loop 2 recAnnLangCode.Ann_Lang assign to var2
var2 := recAnnLangCode.Ann_Lang;
// if loop 3 recAnnLangCode.Ann_Lang assign to var2
var3 := recAnnLangCode.Ann_Lang;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Debug :: Inside Exception because data not found ' );
END;
DECLARE n_counter NUMBER := 0;
BEGIN
LOOP
n_counter := n_counter + 1;
DBMS_OUTPUT.PUT_LINE(n_counter);
IF n_counter = 5 THEN
EXIT;
END IF;
END LOOP;
END;
I did it like this.
maybe you are looking for something like
declare
type a_type is table of recAnnLang.Ann_Lang%type index by pls_integer;
val a_type;
begin
for recAnnLang in getLang(var_non_subscribe) loop
val(nvl(val.last, 0) + 1) := recAnnLang.Ann_Lang;
end loop;
for i in 1 .. val.last loop
dbms_output.put_line(val(i));
end loop;
end;
maybe,if getlang is an explicit cursor,you may think of using rownum in the cursor query select clause and use it as the counter.

How to loop through a delimited list in Oracle PLSQL

I am working on an Oracle procedure that calls another procedure within it. One of my parameters (parm1) can contain one or more values in a comma separated list. How can I loop through these values to pass them one at a time to another procedure?
Here is an example of what I would like it to do:
When Parm1 = 123,312
callProcedure2(123)
callProcedure2(321)
-or-
When Parm1 123
callProcedure2(123)
I think this can be accomplished using a loop but I can't figure out how to get it to use each value as a separated call within the loop.
Any help would be appreciated!
Thanks!
CURSOR V_CUR IS
select regexp_substr(Parm1 ,'[^,]+', 1, level) As str from dual
connect by regexp_substr(Parm1, '[^,]+', 1, level) is not null;
This curor will give you result like this
123
321
Now iterate the cursor and call the procedure in loop.
For i IN V_CUR
LOOP
callProdcedure2(i.str);
END LOOP;
Just loop through substrings:
declare
parm1 varchar2(1000) := '123,234,345,456,567,789,890';
vStartIdx binary_integer;
vEndIdx binary_integer;
vCurValue varchar2(1000);
begin
vStartIdx := 0;
vEndIdx := instr(parm1, ',');
while(vEndIdx > 0) loop
vCurValue := substr(parm1, vStartIdx+1, vEndIdx - vStartIdx - 1);
-- call proc here
dbms_output.put_line('->'||vCurValue||'<-');
vStartIdx := vEndIdx;
vEndIdx := instr(parm1, ',', vStartIdx + 1);
end loop;
-- Call proc here for last part (or in case of single element)
vCurValue := substr(parm1, vStartIdx+1);
dbms_output.put_line('->'||vCurValue||'<-');
end;
There is a utility procedure COMMA_TO_TABLE and array type DBMS_UTILITY.UNCL_ARRAY dedicated for this task. Since Oracle 10g.
It is well document here.
Here is a sample solution:
SET SERVEROUTPUT ON
DECLARE
csvListElm VARCHAR2(4000) := 'elm1, elm2,elm3 ,elm4 , elm5';
csvListTable DBMS_UTILITY.UNCL_ARRAY;
csvListLen BINARY_INTEGER;
currTableName VARCHAR2(222);
BEGIN
DBMS_UTILITY.COMMA_TO_TABLE(csvListElm, csvListLen, csvListTable);
FOR csvElm IN 1..(csvListTable.COUNT - 1) LOOP
dbms_output.put_line('-- CSV element : <'||csvListTable(csvElm)||'>');
dbms_output.put_line('-- Trimmed CSV element: <'||trim(csvListTable(csvElm))||'>');
END LOOP;
END;
/
Sample output:
-- CSV element : <elm1>;
-- Trimmed CSV element: <elm1>;
-- CSV element : < elm2>;
-- Trimmed CSV element: <elm2>;
-- CSV element : <elm3 >;
-- Trimmed CSV element: <elm3>;
-- CSV element : <elm4 >;
-- Trimmed CSV element: <elm4>;
-- CSV element : < elm5>;
-- Trimmed CSV element: <elm5>;
It is possible to use a function that you can use in a for loop (without regexp for ThinkJet):
Create a type and function
CREATE OR REPLACE TYPE t_my_list AS TABLE OF VARCHAR2(100);
CREATE OR REPLACE
FUNCTION cto_table(p_sep in Varchar2, p_list IN VARCHAR2)
RETURN t_my_list
AS
l_string VARCHAR2(32767) := p_list || p_sep;
l_sep_index PLS_INTEGER;
l_index PLS_INTEGER := 1;
l_tab t_my_list := t_my_list();
BEGIN
LOOP
l_sep_index := INSTR(l_string, p_sep, l_index);
EXIT
WHEN l_sep_index = 0;
l_tab.EXTEND;
l_tab(l_tab.COUNT) := TRIM(SUBSTR(l_string,l_index,l_sep_index - l_index));
l_index := l_sep_index + 1;
END LOOP;
RETURN l_tab;
END cto_table;
/
Then how to call it in the for loop:
DECLARE
parm1 varchar2(4000) := '123,234,345,456,567,789,890';
BEGIN
FOR x IN (select * from (table(cto_table(',', parm1)) ) )
LOOP
dbms_output.put_line('callProdcedure2 called with ' || x.COLUMN_VALUE);
callProdcedure2(x.COLUMN_VALUE);
END LOOP;
END;
/
Notice the default name COLUMN_VALUE given by Oracle, which is necessary for the use I want to make of the result.
Result as expected:
callProdcedure2 called with 123
callProdcedure2 called with 234
...

How to declare and display a variable in Oracle

I would like to declare and display a variable in Oracle.
In T-SQL I would do something like this
DECLARE #A VARCHAR(10) --Declares #A
SELECT #A = '12' --Assigns #A
SELECT #A --Displays #A
How can I do this in Oracle.
If you're talking about PL/SQL, you should put it in an anonymous block.
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
If using sqlplus you can define a variable thus:
define <varname>=<varvalue>
And you can display the value by:
define <varname>
And then use it in a query as, for example:
select *
from tab1
where col1 = '&varname';
If you are using pl/sql then the following code should work :
set server output on -- to retrieve and display a buffer
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
/
-- this must be use to execute pl/sql script
Make sure that, server output is on otherwise output will not be display;
sql> set serveroutput on;
declare
n number(10):=1;
begin
while n<=10
loop
dbms_output.put_line(n);
n:=n+1;
end loop;
end;
/
Outout:
1
2
3
4
5
6
7
8
9
10
Did you recently switch from MySQL and are now longing for the logical equivalents of its more simple commands in Oracle? Because that is the case for me and I had the very same question. This code will give you a quick and dirty print which I think is what you're looking for:
Variable n number
begin
:n := 1;
end;
print n
The middle section is a PL/SQL bit that binds the variable. The output from print n is in column form, and will not just give the value of n, I'm afraid. When I ran it in Toad 11 it returned like this
n
---------
1
I hope that helps

Resources