i Have this oracle procedure reading paramater with varchar value,and when i use this parameter value inside the procedure dose not work. Everything will be explained below
CREATE OR REPLACE procedure test_pro(read_batch in varchar2 )
as
v_read_batches varchar2(500);
begin
v_read_batches := '''' || replace(read_batch, ',', ''',''') || '''';
--v_read_batches VALUE IS '100','1000','11','9200'
SELECT CODE,BANK_NAME_ARABIC,BANK_CODE,to_number(BATCH_ID)BATCH_ID FROM (select 1 CODE,PB.BANK_NAME_ARABIC ,to_char(PB.BANK_CODE)BANK_CODE,
CASE PB.BANK_CODE
WHEN 1000
THEN 1000
WHEN 100
THEN 100
ELSE 9200
END batch_id
from BANKS PB
WHERE PB.BANK_CODE IN (1000,100,11200)
union
SELECT 2 CODE,'Other Banks' other_banks,listagg(PB.BANK_CODE , ', ')
within group(order by PB.BANK_CODE ) as BANK_CODE, 11 batch_id
FROM BANKS PB
WHERE PB.BANK_CODE NOT IN (1000,100,9200))
WHERE to_char(BATCH_ID) IN (v_read_batches)
end test_pro;
Problem is when i put v_read_batches inside the sql condition it did not returen any value, when i execute
the below sql alone with same value in v_read_batches variable it works and reture the values !!
SELECT CODE,BANK_NAME_ARABIC,BANK_CODE,to_number(BATCH_ID)BATCH_ID
FROM (select 1 CODE,PB.BANK_NAME_ARABIC
,to_char(PB.BANK_CODE)BANK_CODE, CASE PB.BANK_CODE
WHEN 1000
THEN 1000
WHEN 100
THEN 100
ELSE 9200 END batch_id from BANKS PB WHERE PB.BANK_CODE IN (1000,100,11200)
union SELECT 2 CODE,'Other Banks' other_banks,listagg(PB.BANK_CODE ,
', ') within group(order by PB.BANK_CODE ) as BANK_CODE, 11 batch_id
FROM BANKS PB WHERE PB.BANK_CODE NOT IN (1000,100,9200))
WHERE to_char(BATCH_ID) IN ('100','1000','11','9200')
You cannot build a string like this and hope to use it iin an IN statement. The elements in an IN clause are static, ie, if you code
col in ('123,456')
then we are looking for COL to match the string '123,456' not the elements 123 and 456.
You can convert your input string to rows via some SQL, eg
create table t as select '123,456,789' acct from dual
select distinct (instr(acct||',',',',1,level)) loc
from t
connect by level <= length(acct)- length(replace(acct,','))+1
Having done this, you could alter your procedure so that your
WHERE batch_id in (read_batch)
becomes
WHERE batch_id in (select distinct (instr(:batch||',',',',1,level)) loc
from t
connect by level <= length(:batch)- length(replace(:batch,','))+1
)
In the general sense, never let an input coming from the outside world be folded directly into a SQL statement. You create the risk of "SQL Injection" which is the most common way people get hacked.
Full video demo on the string-to-rows technique here:
https://youtu.be/cjvpXL3H64c?list=PLJMaoEWvHwFIUwMrF4HLnRksF0H8DHGtt
Related
I have a multi select enabled select list. I want to use all the selected ids inside an IN () operator in pl/sql query. Selected values are returned as below,
"1","5","4"
I want to use em as numbers as below,
1,5,4
My query is like,
UPDATE EMPLOYEE SET EMPSTAT = 'Active' WHERE EMPID IN (:P500_EMPIDS);
This is the employee table:
SQL> select * from employee;
EMPID EMPSTAT
---------- --------
1 Inactive
2 Inactive
4 Inactive
5 Inactive
SQL>
This is a way to split comma-separated values into rows (not into a list of values you'd use in IN!). Note that:
line #3: REPLACE function replaces double quotes with an empty string
line #3: then it is split into rows using REGEXP_SUBSTR with help of hierarchical query
SQL> with test (col) as
2 (select '"1","5","4"' from dual)
3 select regexp_substr(replace(col, '"', ''), '[^,]+', 1, level) val
4 from test
5 connect by level <= regexp_count(col, ',') + 1;
VAL
--------------------
1
5
4
SQL>
Usually multiselect items have colon-separated values, e.g. 1:5:4. If that's really the case, regular expression would look like this:
regexp_substr(col, '[^:]+', 1, level) val
Use it in Apex as:
update employee e set
e.empstat = 'Active'
where e.empid in
(select regexp_substr(replace(:P1_ITEM, '"', ''), '[^,]+', 1, level)
from dual
connect by level <= regexp_count(:P1_ITEM, ',') + 1
);
Result is:
3 rows updated.
SQL> select * from employee order by empid;
EMPID EMPSTAT
---------- --------
1 Active
2 Inactive
4 Active
5 Active
SQL>
Try it.
Thanks for helping everyone.Please check this and tell me if anything is wrong. I found a solution as below,
DECLARE
l_selected APEX_APPLICATION_GLOBAL.VC_ARR2;
BEGIN
l_selected := APEX_UTIL.STRING_TO_TABLE(:P500_EMPIDS);
FOR i in 1 .. l_selected.count LOOP
UPDATE EMPLYEE SET EMPSTATUS = 'ACTIVE' WHERE EMPID = to_number(l_selected(i));
END LOOP;
END;
You can use the API apex_string for this. If you want to use the IN operator you'll have to use EXECUTE IMMEDIATE because you cannot use a concatenated string in an IN operator.
Instead what you could do is the following:
DECLARE
l_array apex_t_varchar2;
BEGIN
l_array := apex_string.split(p_str => :P500_EMPIDS, p_sep => ':');
FOR i IN 1..l_array.count LOOP
UPDATE EMPLOYEE SET EMPSTAT = 'Active' WHERE EMPID = l_array(i);
END LOOP;
END;
Explanation: convert the colon separated list of ids to a table of varchar2, then loop through the elements of that table.
Note that I'm using ":" as a separator, that is what apex uses for multi selects. If you need "," then change code above accordingly.
Note that you can use apex_string directly within an update statement, so the answer of Koen Lostrie could be modified to not need a loop:
UPDATE EMPLOYEE
SET EMPSTAT = 'Active'
WHERE EMPID IN (
select to_number(trim('"' from column_value))
from table(apex_string.split(:P500_EMPIDS,','))
);
Testcase:
with cte1 as (
select '"1","2","3"' as x from dual
)
select to_number(trim('"' from column_value))
from table(apex_string.split((select x from cte1),','))
How to get the failing column name for ora-01722: invalid number when inserting.
I have two tables. Table A - all hundred columns are varchar2 and table B one half varchar2 other half number.
table A ( c1 varchar2(100), c2 varchar2(100) ... c100 varchar2(100) )
table B ( c1 number, c2 number .. c49 number, c50 varchar2(100), c51 varchar2(100) ... c100 varchar2(100) )
Need to load table a into table b. the mapping is not 1 to 1. column names are not matching.
insert into b ( c1, c2, c3, c4 .. c50,c51 .. c100 ) select to_number(c20) + to_number(c30), to_number(c10), to_number(c80) .. c4, c5 .. c40 from a.
It takes a lot of time to find the failing column manually in case of ora-01722.
So i tried - log errors into err$_b ('INSERT') reject limit unlimited.
It gives you failing rows, but not the column.
Still need to find the failing column manually . Not much of help.
Tried error handling, but always get 0 offset position with
exception when others then
v_ret := DBMS_SQL.LAST_ERROR_POSITION;
dbms_output.put_line(dbms_utility.format_error_stack);
dbms_output.put_line('Error at offset position '||v_ret);
I could use custom is_number function to check if number before inserting.
But in this case I will get null target value not knowing if source is empty or it has wrong number format.
It is possible automate the process by running data check to find failing rows and columns.
If mapping is one to one - then simple data dictionairy query could generate the report to show what columns will fail.
select 'select col_name, count(*) rc, max(rowid_col) rowid_example from (' from dual union all
select txt from
(
with s as ( select t.owner, t.table_name, t.column_name, t.column_id
from all_tab_columns s join all_tab_columns t on s.owner =t.owner and s.column_name = t.column_name
where lower(s.table_name) = 'a' and s.data_type = 'VARCHAR2' and
lower(t.table_name) = 'b' and t.data_type = 'NUMBER' )
select 'select ''' || column_name ||''' col_name, rowid rowid_col, is_number('|| column_name || ') is_number_check from ' || owner ||'.'|| table_name ||
case when column_id = (select max(column_id) from s )
then ' ) where is_number_check = 0 group by col_name'
else ' union all' end txt
from s order by column_id
)
If there is no one to one mapping between table columns, then you could define and store the mapping into a separate table and then run the report.
Is there something more oracle could help in finding the failing column?
Are there any better manual ways to quicly find it?
I work on this query and get this error:
Oracle - ORA-01489: result of string concatenation is too long
Some one please help to solve this issue
SELECT LISTAGG(RCRDNUM) WITHIN GROUP (ORDER BY RCRDNUM)
FROM (SELECT (ERR.RCRDNUM || ',') AS RCRDNUM
FROM TABLENAME ERR
INNER JOIN (SELECT UPPER(REGEXP_SUBSTR('No value present for CNTRY_CD column for the record',
'[^,]+', 1, LEVEL)) ERR_MSG
FROM DUAL
CONNECT BY REGEXP_SUBSTR('No value present for CNTRY_CD column for the record',
'[^,]+', 1, LEVEL)
IS NOT NULL) ERRMSG_P
ON (UPPER(ERR.ERRMSG) = ERRMSG_P.ERR_MSG
OR 'No value present for CNTRY_CD column for the record' IS NULL))
If the aggregate list is a string longer than 4000 characters, the string needs to be a CLOB, and you can't use listagg(). However, you can use xmlagg(), which does not have the 4000 character limit. The result must be a CLOB though - and it is cast as CLOB in the solution.
. Here is a proof-of-concept; I will let you adapt it to your situation.
with a (id,val) as (select 10, 'x' from dual union all select 20, 'abc' from dual)
select listagg(val, ',') within group (order by id) as l_agg,
rtrim( xmlcast( xmlagg( xmlelement(e, val || ',') order by id) as clob), ',')
as clob_agg
from a
;
Output
L_AGG CLOB_AGG
---------- ----------
x,abc x,abc
In Oracle's SQL queries, strings (columns of type VARCHAR) are limited to 4000 characters. Obviously, your query creates longer strings and therefore fails. This can easily happen with LISTAGG.
Should your query really return such long strings? If not, you need to work on your query.
If you really need values longer than 4000 characters, you can try to use CLOB instead of VARCHAR by using a custom user-defined aggregation function. Tom Kyte has an example in one of his questions.
I am trying to reverse a string without using REVERSE function. I came across one example which is something like:
select listagg(letter) within group(order by lvl)
from
(SELECT LEVEL lvl, SUBSTR ('hello', LEVEL*-1, 1) letter
FROM dual
CONNECT BY LEVEL <= length('hello'));
Apart from this approach,is there any other better approach to do this?
If you're trying to avoid the undocumented reverse() function you could use the utl_raw.reverse() function instead, with appropriate conversion too and from RAW:
select utl_i18n.raw_to_char(
utl_raw.reverse(
utl_i18n.string_to_raw('Some string', 'AL32UTF8')), 'AL32UTF8')
from dual;
UTL_I18N.RAW_TO_CHAR(UTL_RAW.REVERSE(UTL_I18N.STRING_TO_RAW('SOMESTRING','AL32UT
--------------------------------------------------------------------------------
gnirts emoS
So that is taking an original value; doing utl_i18n.string_to_raw() on that; then passing that to utl_raw.reverse(); then passing the result of that back through utl_i18n.raw_to_char().
Not entirely sure how that will cope with multibyte characters, or what you'd want to happen to those anyway...
Or a variation from the discussion #RahulTripathi linked to, without the character set handling:
select utl_raw.cast_to_varchar2(utl_raw.reverse(utl_raw.cast_to_raw('Some string')))
from dual;
UTL_RAW.CAST_TO_VARCHAR2(UTL_RAW.REVERSE(UTL_RAW.CAST_TO_RAW('SOMESTRING')))
--------------------------------------------------------------------------------
gnirts emoS
But that thread also notes it only works for single-byte characters.
You could do it like this:
with strings as (select 'hello' str from dual union all
select 'fred' str from dual union all
select 'this is a sentance.' from dual)
select str,
replace(sys_connect_by_path(substr (str, level*-1, 1), '~|'), '~|') rev_str
from strings
where connect_by_isleaf = 1
connect by prior str = str --added because of running against several strings at once
and prior sys_guid() is not null --added because of running against several strings at once
and level <= length(str);
STR REV_STR
------------------- --------------------
fred derf
hello olleh
this is a sentance. .ecnatnes a si siht
N.B. I used a delimiter of ~| simply because that's something unlikely to be part of your string. You need to supply a non-null delimiter to the sys_connect_by_path, hence why I didn't just leave it blank!
SELECT LISTAGG(STR) WITHIN GROUP (ORDER BY RN DESC)
FROM
(
SELECT ROWNUM RN, SUBSTR('ORACLE',ROWNUM,1) STR FROM DUAL
CONNECT BY LEVEL <= LENGTH('ORACLE')
);
You can try using this function:
SQL> ed
Wrote file afiedt.buf
1 with t as (select 'Reverse' as txt from dual)
2 select replace(sys_connect_by_path(ch,'|'),'|') as reversed_string
3 from (
4 select length(txt)-rownum as rn, substr(txt,rownum,1) ch
5 from t
6 connect by rownum <= length(txt)
7 )
8 where connect_by_isleaf = 1
9 connect by rn = prior rn + 1
10* start with rn = 0
SQL> /
Source
select listagg(rev)within group(order by rownum)
from
(select substr('Oracle',level*-1,1)rev from dual
connect by level<=length('Oracle'));
I need to write one procedure to pick the record for given rows
for example
procedure test1
(
start_ind number,
end_ind number,
p_out ref cursor
)
begin
opecn p_out for
select * from test where rownum between start_ind and end_ind;
end;
when we pass start_ind 1 and end_ind 10 its working.But when we change start_ind to 5
then query looks like
select * from test where rownum between 5 and 10;
and its fails and not shows the output.
Please assist how to fix this issue.Thanks!
The rownum is assigned and then the where condition evaluated. Since you'll never have a rownum 1-4 in your result set, you never get to rownum 5. You need something like this:
SELECT * FROM (
SELECT rownum AS rn, t.*
FROM (
SELECT t.*
FROM test t
ORDER BY t.whatever
)
WHERE ROWNUM <= 10
)
WHERE rn >= 5
You'll also want an order by clause in the inner select, or which rows you get will be undefined.
This article by Tom Kyte pretty much tells you everything you need to know: http://www.oracle.com/technetwork/issue-archive/2006/06-sep/o56asktom-086197.html
SELECT *
from (SELECT rownum AS rn, t.*
FROM MyTable t
WHERE ROWNUM <= 10
ORDER BY t.NOT-Whatever
-- (its highly important to use primary or unique key of MyTable)
WHERE rn > 5
As a hint, :
Typically we use store-procedures for data validation, access control, extensive or complex processing that requires execution of several SQL statements. Stored procedures may return result sets, i.e. the results of a SELECT statement. Such result sets can be processed using cursors, by other stored procedures, by associating a result set locator, or by applications
I think you are going to use the ruw-number to fetch paged queries.
Try to create a generic select query based on the idea mentioned above.
Two possibilities:
1) Your table is an index-organized table. So its data is sorted. You would select those first rows you want to avoid and based on that get the next rows you are looking for:
create or replace procedure get_records
(
vi_start_ind integer,
vi_end_ind integer,
vo_cursor out sys_refcursor
) as
begin
open vo_cursor for
select *
from test
where rownum <= vi_end_ind - vi_start_ind + 1
and rowid not in
(
select rowid
from test
where rownum < vi_start_ind
)
;
end;
2) Your table is not index-organized, which is normally the case. Then its records are not sorted. To get records m to n, you would have to tell the system what order you have in mind:
create or replace procedure get_records
(
vi_start_ind number,
vi_end_ind number,
vo_cursor out sys_refcursor
) as
begin
open vo_cursor for
select *
from test
where rownum <= vi_end_ind - vi_start_ind + 1
and rowid not in
(
select rowid from
(
select rowid
from test
order by somthing
)
where rownum < vi_start_ind
)
order by something
;
end;
All this said, think it over what you want to achieve. If you want to use this procedure to read your table block for block, keep in mind that it will read the same data again and again. To know what rows 1,000,001 to 1,000,100 are, the dbms must read through one million rows first.