Dynamic WHERE Clause with multiple ORs
I need to build a dynamic SQL statement such as the clause WHERE looks / works as follows:
WHERE x LIKE '%1% ' OR LIKE '%2% ' x OR x LIKE '%3%...
I can do the above, no problem, but I wonder if there is a better way?
Thank you
Mark
Hi, Mark,.
You should not need dynamic SQL for that.
For example, if you are still interested in substrings of characters suingle, and you get entry as a unique string called str (e.g. '123' it which means you want to find the rows where x contains '1', '2' or 3'), so you could say:
...
WHERE (x REGEXP_LIKE
, '[' || str || ']'
)
I hope that answers your question.
If not, post a small example data (CREATE TABLE and INSERT statements), a few entries and also post the desired results of each input given the same data.
Explain, using specific examples, how you get these results from these data.
Always say what version of Oracle you are using (for example, 11.2.0.2.0).
See the FAQ forum: https://forums.oracle.com/message/9362002#9362002
Tags: Database
Similar Questions
-
Need help with dynamic where clause.
Hello world. I'm kind of a novice with PL/SQL, so please be patient with me. I am building a web application using Weblogic Oracle 11 g and Oracle database.
To make a long story short, I need to generate the complex dynamic WHERE clause. I don't know what will be the name of the column or the operator of comparison or the value will be until the moment of execution.
I'm not 100% certain, but I think I need to use dynamic SQL statements. Unless there is a better way to do it.
I'm sure that using dynamic SQL opens me up to SQL injection attacks if I use simple string concatenation. I would like to use bind variable if possible.
In any case, it seems like trying to build a dynamic where clause does not seem to work as I want it would be...
bv1 := 'colA = 5 and colB >= 9'; query_str := 'SELECT * FROM view WHERE :bv1'; OPEN CUR FOR query_str USING bv1;
The code above pours out when I try to run it.
Is there a way to build dynamic where the provisions without the use of concatenation of simple string that leaves me open to attacks by SQL injection?
Thank you
Hello. I have read briefly upward on things, you suggested, but it seems a bit abstract for me since I was a novice.
Can you give us an explanation or an example of how to use it to accomplish what I need to do?
Do ypu really plan create a query with a WHERE clause that contains a predicate for all possible columns?
Variable bind offer performance when the same query is executed several times with different values for bind variables.
Select * from emp where empno =: v_empno
After the first run Oracle will always be this query in the library cache. The next running can use the version of the cache even if the bind value is different.
Select * from emp where empno =: v_empno;
Select * from emp where ename =: v_ename;
Select * from emp where sal =: v_sal;
Each one is a DIFFERENT query. Yes - each of them uses a variable binding, but queries are different.
So, if your username select EMPNO, an '=', and a value from the first query can be executed. But the next time that the user can select the ENAME column so that 'stored' first request may not be used given that the query does not match.
The third time your user selects SAL so none of the first two queries can be used in the library cache. The use of bind variables gives performance during the SAME QUERY is used multiple times with DIFFERENT values for the variable binding. Oracle is not to analyze the hard query everything simply because the VALUE is different.
So bind variables do not help you if most of the queries were completely DIFFERENT sets of predicates. And SYS_CONTEXT will not help either since that simply provides a way to define binds the values of the variables.
Just for the simple example above, there are at least SIX possible combinations of columns that could choose your user name: empno, ename, sal, empno ename, empno & sal, ename & sal
-
Very Urgent: Setting dynamic where clause for Popup list VO
Hello world
It is a very urgent requirement please help as soon as possible.
I have a custom page in iSupplier. I created two supplier site, number of PO fields.
Site of beg - choice of Message and PO number - Message LOV of entry
I have a named VO under xxisupplier.oracle.apps.pos.home.poplist.server for site begging and xxisupplier.oracle.apps.pos.home.lov.server for PO number.
I have joined these two VO AM homepage.
Now the question is
1. I want to restrict these VO vendor_id-based so I'll put dynamically where clause for these two VO of in my CO
VO SITE PROVIDER QUERY
SELECT POVs.vendor_site_code site, pov.vendor_id
OF po_vendors pov, povs po_vendor_sites_all
WHERE pov.vendor_id = povs.vendor_id
AND TRUNC (povs.inactive_date) IS NULL
PO NUMBER LOV QUERY VO
SELECT DISTINCT ai.invoice_num, ai.vendor_id, ai.invoice_date, poh.segment1
AI ap_invoices_all,.
help ap_invoice_distributions_all,
po_headers_all poh,
po_distributions_all pda,
Al ap_lookup_codes
WHERE aid.po_distribution_id = pda.po_distribution_id
AND ai.invoice_id = aid.invoice_id
AND poh.po_header_id = pda.po_header_id
AND ai.invoice_type_lookup_code = al.lookup_code
AND al.lookup_type = 'INVOICE TYPE'
I am creating where cluase as below in CO
If (vendor_id1! = null)
{
System.out.println ("vendor_id:" + vendor_id1);
OAViewObjectImpl vo = (OAViewObjectImpl) am.findViewObject ("PO_LOV_VO");
if(vo!=null)
{
vo.clearCache ();
VO. Reset();
System.out.println ("inside IN. VO:" + vendor_id1);
vo.setWhereClause (null);
vo.setWhereClause ("vendor_id =: 1");
vo.setWhereClauseParams (null);
vo.setWhereClauseParam(0,vendor_id1);
vo.setOrderByClause ("invoice_date DESC");
String INVQRY = vo.getQuery ();
System.out.println ("INVQRY:" + INVQRY);
vo.executeQuery ();
VO. First();
System.out.println ("after the query appear" + vo.getRowCount ());
}
OAViewObjectImpl sitevo1 = (OAViewObjectImpl) am.findViewObject ("SUPPLIER_SITE_VO1");
if(sitevo1!=null)
{
sitevo1.clearcache ();
sitevo1. Reset();
System.out.println ("Interior site:" + vendor_id1);
sitevo1.setWhereClause (null);
sitevo1.setWhereClause ("vendor_id =: 1");
sitevo1.setWhereClauseParams (null);
sitevo1.setWhereClauseParam(0,vendor_id1);
String SITEQRY = sitevo1.getQuery ();
System.out.println ("SITEQRY:" + SITEQRY);
sitevo1. ExecuteQuery();
sitevo1. First();
System.out.println ("after the query appear" + sitevo1.getRowCount ());
}
Here he works for the purchase order number but the where cluase does not work for Supplier Site. Please help as soon as possible.
2 and also if supplier site to return multiple values then this field should show as messagechoice. If it returns a single value, then it should be the style text message
How can I achieve this.
Thank you
CSKTry
vo.setWhereClause ("IN vendor_id (" + vendor_id_qry + ")" ");
vendor_id_qry is the query that retrieves the list of provider IDS. You don't need to put the vendor column id as whereClauseParam unless you want to have IN the clause in your query of VO and pass the list as 1,2,3 values to the parameter.
Thank you
Shree -
Dear all,
I have a problem in the dynamic where clause in the OPS.
I have a VO query as below:
SELECT desc, ccuid, containid, XXXTMP conainline
I'll put whereclause as below:
VO.setwhereclause ("containid '101' =" + "order by containline desc")
so the question is request forms as below:
SELECT desc, ccuid, containid, XXXTMP conainline
(where containid = '101' containline desc order) -query gives question, adding the command from the inside of the caliper
Ideally, order by clause should come outside of the Stirrup.
so, how do I do order by clause order side where clasue or how do I remove the stand before the where clause. So I need the query as below:
SELECT desc, ccuid, containid, XXXTMP conainline
(where containid = '101' containline desc order)
SELECT desc, ccuid, containid, conainline from XXXTMP where containid = '101' containline desc order
or
SELECT desc, ccuid, containid, XXXTMP conainline
(where containid = '101') order by containline desc
Thank you
Hello
Solution 1-
You can use "setOrderByClause (containline desc);" so that it will get out of Where clause.
Solution 2-
Instead of dynamically add Whereclause, you can bind the variable as below-
Query in VO-
SELECT desc, ccuid, containid, conainline from XXXTMP where containid =: 1 containline desc order
In VOImpl-
public void initQuery (String variable)
{
clearCache();
setMaxFetchSize(-1);
setWhereClause (null);
setWhereClauseParams (null);
setWhereClauseParam (0, variable);
executeQuery();
}
Vall of this VOImpl method, and pass the variable value. It will work according to your requirement.
Thank you
Kone
-
Using the Case statement in Where clause with operator
Hi all
I'm doing the following work (this is just a simple version of what I'll eventually need):
Sorry, I forgot how to use the code tags...
and li. MAJOR_ACCT in case
When: prompt = 'Energy' then ('9320906 ', ' 9321471')
end
Problem is that I get a missing closing parenthesis error.
Wouldn't - that evaluate against a value(as below) it works fine:
and li. MAJOR_ACCT in case
When: prompt = 'Energy' then ('9320906')
end
Any thoughts? Is it possible to use a box (or decode) in an In clause with multiple values? I tried to use decode as well and get the same results.
Thank you.
Darren.What:
and ( case when :prompt = 'Energy' and li.MAJOR_ACCT in ('9320906', '9321471') then 1 when :prompt = 'Vehicle' and li.MAJOR_ACCT in ('9812180', '9812320') then 1 when :prompt = 'Meals' and li.MAJOR_ACCT in ('983120', '983452') then 1 end ) = 1
-
Passing the value of the where clause with the page
Dear friends,
I have a requirement like when I select a selection list value I should pass this value to sql query where clause without submitting the page
ex I have a select like: P1_Dept guess I selects the value 10 in this
then I have a query select * from emp where deptno =: P1_Dept.
DB. ORACLE 11G
APEX 4.1.1.00.23
is this possible? can someone help me please in this topic
Thanks and greetings
Vballeda
Suppose we have the selection list with the name P1_DEPT and query for report
select * from emp where deptno = :P1_DEPT
We create dynamic Action on the evolution of the P1_DEPT point. We will need two real actions:
1-> set value action
Set the Type - > body of the PL/SQL function
The function of body - > return 1;
Page item to submit-> P1_DEPT
Change to delete-> Yes event
Selecttion Type-> trigger element
2. action-> Refresh
Selecttion Type-> region
Region-> your region of report
-
Construction of a dynamic Where clause:
Hi experts,
In my environment real time in the java code for a statement select query they they add dynamically to the place where clause and retrieve the data using hybernet. I want to do it in PL/SQ
(1) is it possible?
(2) how can I do this
(3) can provide you with the example of document or for example for this one. Please help me>
In my environment real time in the java code for a statement select query they they add dynamically to the place where clause and retrieve the data using hybernet. I want to do it in PL/SQ(1) is it possible?
>
Non - Oracle can not recover the data using hybernet.
>
(2) how can I do this
>
You can't - see response to #1 above
>
(3) can provide you with the example of document or for example for this one. Please help me
>
Not until give you an example of a document or an example of what you speak again. -
Hi experts,
I use Oracle Database 10 g Enterprise Edition Release 10.2.0.3.0 - 64 bit
I have to write a MS which has dynamic where clouse this where to accept the form of the value of the parameter.
This is my SP and Eroor.
can you please let me know where I hurt m.CREATE OR REPLACE PACKAGE PKG_EW_PROJection_QUERY AS PROCEDURE PR_PROJECTION_QUERY(PD_AS_OF_DATE IN DATE, PV_MEMBER_CODE IN VARCHAR2, PV_TYPE_LIST IN VARCHAR2, -- here i have different input paramater and depending on this my where where clouse will be change -- so my input string look like('abd,cfd,fgh') if it abd then my where condition different and if cfd -- then where condition different. CUR_PROJECTION_OUT OUT SYS_REFCURSOR); END PKG_EW_PROJection_QUERY; / CREATE OR REPLACE PACKAGE BODY PKG_EW_PROJection_QUERY AS PROCEDURE PR_PROJECTION_QUERY(PD_AS_OF_DATE IN DATE, PV_MEMBER_CODE IN VARCHAR2, PV_TYPE_LIST IN VARCHAR2, CUR_PROJECTION_OUT OUT SYS_REFCURSOR) IS sql_stmt varchar2(1000); BEGIN IF PV_TYPE_LIST LIKE '%GRA-PRINCIPAL%' THEN SQL_STMT := 'SELECT P.FIC_MIS_DATE, P.V_MEMBER_CODE, P.V_TXN_DESC, P.N_AMOUNT_LCY FROM FCT_PROJECTIONS P, DIM_TXN_DESC D'; SQL_STMT := SQL_STMT ||' WHERE P.N_RESOURCE_GROUP_NBR=D.N_RESOURCE_NBR AND P.V_TXN_CODE=D.V_TXN_CODE'; SQL_STMT := SQL_STMT ||' AND P.FIC_MIS_DATE ='||PD_AS_OF_DATE; SQL_STMT := SQL_STMT ||' AND V_MEMBER_CODE='||PV_MEMBER_CODE; SQL_STMT := SQL_STMT ||' AND D.V_BRANCH_CODE=' ||'GRA'; SQL_STMT := SQL_STMT ||' AND D.V_TXN_CODE='||'REP'; end if; OPEN CUR_PROJECTION_OUT FOR SQL_STMT; END PR_PROJECTION_QUERY; END PKG_EW_PROJection_QUERY; and i got below error Error starting at line 2 in command: EXEC PKG_EW_PROJection_QUERY.PR_PROJECTION_QUERY('31-JUL-2011','PAK','GRA-PRINCIPAL',:CUR_POS_OUT) Error report: ORA-00604: error occurred at recursive SQL level 1 ORA-01003: no statement parsed 00604. 00000 - "error occurred at recursive SQL level %s" *Cause: An error occurred while processing a recursive SQL statement (a statement applying to internal dictionary tables). *Action: If the situation described in the next error on the stack can be corrected, do so; otherwise contact Oracle Support. CUR_POS_OUT ------
If you need more information please let me know.
Thank you
Ritesh.You do not have anything in your example that requires dynamic sql.
Consider this:
declare cursor my_cur (val1 varchar2, val2 number) is select column1, column 2 from table1 where column1 = val1 and column2 = val2; begin if your_condition then --process the cursor declared above for cur_rec in my_cur ('ABC', 12) loop do something end loop; end if; end;
In your example, you're just concatenate strings together, which could be managed with variables.
-
Interactive report dynamic where clause
Hello!
Is it possible that a report interactive sql source can have a where clause clause that is built dynamically?
MarcMarc:
You could empty the record-ID set in a collection of the APEX.
Change the IR query to add a join for this collection. Something likeselect c1, c2,c3... from main_tab a, apex_collections b where b.name='RECORD_IDS' and a.pk_col=b.to_number(c001)
More about APEX collections can be found at
http://download.Oracle.com/docs/CD/E14373_01/AppDev.32/e11838/advnc.htm#insertedID4CITY
-
where clause with reg_exp
Hello
My query is...
The string is "1,2,3"...
output must be '1', ' 2 ', ' 3',
Please help me...!
Concerning
SA
The guru gave the solution...
But, I have to use this condition in Where clause on my request. If I put in which the value of the clause does not appear. Any help on that...! Please, I beg you.select REGEXP_REPLACE('1, 2, 3', '([0-9]+)', '''\1''') from dual;
Concerning
SAHello
Query: SELECT "' | REPLACE ('1,2,3',',' "',"'). "' val FROM DUAL;
will convert '1,2,3' string '1', ' 2 ', 3'.
Run the sub queries first and then run a select statement.
CREATE TABLE sample_table
(
col_a VARCHAR2 (3)
);INSERT INTO sample_table
VALUES ('1');INSERT INTO sample_table
VALUES ('2');INSERT INTO sample_table
VALUES ('3');INSERT INTO sample_table
VALUES ('4');INSERT INTO sample_table
VALUES ('5');COMMIT;
SELECT col_a
OF sample_table
WHERE INSTR ((SELECT ''' ||)) REPLACE ('1,2,3',',' "',"'). "' val
THE DOUBLE).
col_a
) > 0;The select statement above will give you the desired result of "sample_table" as below.
COL_A
1
2
3Kind regards
Big Boss -
Dynamic where clause of user defined reports
Hello everyone,
Is there a way to make / calculate a where clause clause in a user defined report according to the value of some bind variables?
I am trying to remove where the terms of my application if the binding variable is not defined.
previously, I did something as
AND tab.column = nvl (: colum_bin, tab.column)
but there are problems in implementation plans.
StoneSure that you can not, but how about you to rewrite the NVL in
OR: colum_bin IS NULL
Hope that helps,
K. -
Oracle OFA customization list of values (LOV) mapping in Where clause with variables
Hi all
I have a requirement to add the condition of the UOM LOV I don't understand under conditions in LOV for example mcc.inventory_item_id =: 1 what: 1 means? and how the system look at the value in: 1? if I have to add the condition to the middle which number should I use?
SELECT * FROM (SELECT distinct muc.unit_of_measure unit_meas_lookup_code, muc.unit_of_measure_tl unit_meas_lookup_code_tl, muc.description, muc.uom_class, muom.uom_code FROM mtl_uom_conversions_val_v muc, mtl_units_of_measure muom WHERE (muc.uom_class IN (SELECT mcc.to_uom_class CMC mtl_uom_class_conv_val_v WHERE mcc.inventory_item_id =: 1) muc.uom_class = GOLD: 2), AND (muc.item_id =) ((: 3 GOLD muc.item_id = 0) AND muc.unit_of_measure = muom.unit_of_measure) QRSLT WHERE ((UPPER (UNIT_MEAS_LOOKUP_CODE_TL) like UPPER(:4) AND (UNIT_MEAS_LOOKUP_CODE_TL like: 5 OR UNIT_MEAS_LOOKUP_CODE_TL as: 6 OR UNIT_MEAS_LOOKUP_CODE_TL as: 7 OR UNIT_MEAS_LOOKUP_CODE_TL as: 8))) ORDER BY upper (unit_meas_lookup_code)
Concerning
A.S.
Hey A.S.,.
Looking more closely at the image you included, it seems that it is already a custom code, it starts with "Xx". You should see if you have the available custom code.
To answer part of your original question ""mcc.inventory_item_id =: 1 what: 1 means? ' " The ': 1 ' is a variable binding in the SQL code. This value is populated at run time by using the "setWhereClauseParam (Bind number, value). You can see the details of the request and the variable linking using JDeveloper and a double-tap on the View object. Again, this should be in the custom code of the object View 'atco.oracle.apps.po.lov.server.XxDocumentUomBothVo '.
I hope this helps.
Thank you
Tim
-
Simple conditional SQL WHERE Clause with two Subselects
Hi SQL Experts,
I need some quick help with a query.
It is a ' select ' for a data source object repository phyiscal table OBI.
So, I can't put in PL/SQL or in stored procedures. I just need
have two conditions / selects different according to the user's role (this information comes
of the session).
The above does not work:-ORA00905. 00000 - 'lack the key word'
SELECT OFFICENO FROM orgunit
WHERE
BOX WHEN "SESSION_VARIABLE' LIKE '% globalmanager %' THEN
ASSIGNEDOFFICES =
(
SELECT DISTINCT ASSIGNEDOFFICES
FROM USERSTABLE INNER JOIN orgunit WE
OrgUnit. KEY = USERSTABLE. OFFICE
WHERE USERSTABLE. USERNAME ='VALUEOF (NQ_SESSION. THE USER)"
)
ON THE OTHER
OFFICENO =
(
SELECT DISTINCT USERSTABLE OFFICENO
INNER JOIN orgunit WE
OrgUnit. KEY = USERSTABLE. OFFICE
WHERE USERSTABLE. USERNAME ='VALUEOF (NQ_SESSION. THE USER)"
)
END;Can anyone help?
Hello
I can't tell what you want to do by looking at the code that do not do. Maybe:
SELECT officeno
For orgunit
WHERE (session_variable LIKE '% globalmanager %'
AND IN assignedofficies
(
SELECT assignedoffices
UserTable U1
JOIN orgunit o1 ON o1.officekey = u1.officekey
WHERE u1.username = ' VALUEOF (NQ_SESSION. THE USER)"
)
)
OR (NVL (session_variable
, '?'
) NOT LIKE '% globalmanager % '.
AND IN officeno
(
SELECT officeno
Of u2 usertable
JOIN orgunit o2 ON o2.officekey = u2.officekey
WHERE u2.username = ' VALUEOF (NQ_SESSION. THE USER)"
)
)
;
There might be a simpler and more efficient way in function your tables and your limit.
The condition u2.username = ' VALUEOF (NQ_SESSION. The USER) "almost certainly not what you really want.
.
Whenever you have any questions, post a small example data (CREATE TABLE and only relevant columns, INSERT statements) for all of the tables involved and also publish outcomes from these data.
Explain, using specific examples, how you get these results from these data.
Always say what version of Oracle you are using (for example, 11.2.0.2.0).See the FAQ forum: https://forums.oracle.com/message/9362002#9362002
-
Hello
I have a table named TEST_TAB that has three columns - COL1, COL2 and COL3.
COL3 PEUVENT having distinct values of 1,2 and 3.
I need select * from TEST_TAB following conditions.
If COL3 has values 1,2 and 3 and select * should return only the rows with COL3 = 1.
If COL3 has no values 1, then select * should return only the rows with COL3 = 2.
IF COL3 is either 1 or 2, then select * should return only the rows with COL3 = 3.
Is it possible to do in a SQL? I prefer a single SQL.
Thank you.
Sajeeva Lacotte.Something like
select * from TEST_TAB where ( COL3 = 1 or ( COL3 = 2 and not exists ( select null from TEST_TAB where col3 = 1 ) ) or ( COL3 = 3 and not exists ( select null from TEST_TAB where col3 in ( 1, 2 ) ) ) )
Anton
-
using where clause with value to hardcode in run immediately
Dear Experts, I use below in the stored procedure make exception.
RUN IMMEDIATELY "REMOVE CC. TB WHERE COL ='HG ";
When the collar is varchar2 (30) DC. TB
Please guide how to use above the statement in the stored procedure
Thank youDBA wrote:
Dear Experts, I use below in the stored procedure make exception.RUN IMMEDIATELY "REMOVE CC. TB WHERE COL ='HG ";
When the collar is varchar2 (30) DC. TB
Please guide how to use above the statement in the stored procedure
Thank you
Why you use dynamic SQL? DELETE statement is a DML statement and its valid inside a PL/SQL block.
So, you can remove the immediate execution and write your DELETE statement directly.
begin delete from cc.tb where col = 'HG'; end;
Maybe you are looking for
-
CloudFlare said allow javascript
When I click on a link on a website to send an email it distracts me to another page that says:"The website where you got to this page is protected by CloudFlare. Email addresses on this page have been hidden to prevent them from accessed by maliciou
-
External hard drive is extremely slow backup
We have an external hard drive connected to our iMac. Time Machine used to store backups, but something happened and he stopped to save on 16 February the hard disk became full and when the reader become unalterable for Time Machine could not delete
-
OfficeJet Pro 8600 N911A: fax wireless
I need to be able to SEND faxes. Is it possible to configure my Fax on my Wireless HP Officejet Pro 8600 model N911A?
-
Satellite L500D-11R - plugged in but not charging
Hello I had a Satellite L500D-11R windows 7 - its fine loads (light orange deep) when it is off, but when running, it will be reduced to an orange flashing light and will not load. in the taskbar windows says its plugged in but not charging - unplugg
-
Windows Mail can suddenly throw up error "Assertion failure"?
On Vista, 32-bit, Windows Mail (which worked perfectly fine) now guard throw up a "Assertion failed!" error when I click on my POP3 Inbox. I can see all the message headers but can't get their reading. Pressing on 'Retry' just quit the program. Nothi