case in PL/SQL where clause statement
- Hello
- I have a research procedure where the user can search on the city, street, zip code.
- I need meet the 6 different combinations as I don't know what value the user will pass.
- It should be checked if the user passes the value or not, and then look on values passed.
- But the procedure below is out.it the slightest mistake can be transformed with if-then-else, but case statement seems much cleaner in the code.
- procedure searchaddress (pc_town IN SEARCHADDRESS. CITY % TYPE,
pc_street IN SEARCHADDRESS. TYPICAL STREET %,
pc_postcode IN SEARCHADDRESS. POSTCODE % TYPE,
pResultSet to ref_cursor) as
Start
Open the pResultset for
Select searchaddress_pk from searchaddress
where
case
When pc_town is null then ((street = pc_street) and (ZipCode = pc_postcode))
When pc_street is null then ((town = pc_town) and (ZipCode = pc_postcode))
When pc_postcode is null then ((town = pc_town) and (street = pc_street))
When pc_town is null and pc_street is null then (postal code = pc_postcode)
When pc_street is null and pc_postcode is null then (city = pc_town)
When pc_town is null and pc_postcode is null then (street = pc_street)
end
end searchaddress;
Thank you
CenterB
A basic concept that is important to understand - sliders aren't 'sets of results' (sets of data in memory). A cursor is a series of executable steps (see plans run to cursor). It's like a program. An extraction run the program and output data. In general, which is repeated until the cursor (aka program) is no longer found the corresponding lines.
A ref cursor is a pointer or a handle for a such slider, passed to a caller, allowing the appellant to interface directly with this slider/program.
The slider more effective to create a search would be one without superfluous code and predicates and filters. Consider the following approach - a beefier PL/SQL procedure, do not try and play little tricks with SQL predicates in an attempt to create one (and probably not optimal) SQL.
(not tested/compiled code)
create or replace procedure SearchAddress( town IN SEARCHADDRESS.TOWN%TYPE, street IN SEARCHADDRESS.STREET%TYPE, postcode IN SEARCHADDRESS.POSTCODE%TYPE, refCur out ref_cursor ) is curHandle integer; res integer; searchSQL varchar2(1000); begin -- create base query searchSQL := 'select searchaddress_pk from searchaddress where 1 = 1 '; -- add dynamic predicates as needed if town is not null then searchSQL := searchSQL || 'and town = :town'; end if; if street is not null then searchSQL := searchSQL || ' and street = :street'; end if; if postcode is not null then searchSQL := searchSQL || ' and postcode = :postcode'; end if; -- create a DBMS_SQL cursor curHandle := DBMS_SQL.open_cursor; DBMS_SQL.parse( curHandle, searchSQL, DBMS_SQL.NATIVE ); -- bind the dynamic bind variables added as predicate values if town is not null then DBMS_SQL.Bind_Variable( curHandle, 'town', town ); end if; if street is not null then DBMS_SQL.Bind_Variable( curHandle, 'street', street ); end if; if postcode is not null then DBMS_SQL.Bind_Variable( curHandle, 'postcode', postcode ); end if; -- execute cursor (to create the cursor program) and pass it back as a ref cursor res := DBMS_SQL.Execute( curHandle ); refCur := DBMS_SQL.To_RefCursor( curHandle ); end;
Tags: Database
Similar Questions
-
Exclude duplicates on SQL where clause statement
Hello!
Are a few posibilities to exclude duplicates do not using aggregate sql in a main select functions?
Priview SQL statement
SELECT * FROM ( select id,hin_id,name,code,valid_date_from,valid_date_to from diaries ) QRSLT WHERE (hin_id = (SELECT NVL(historic_id,id)FROM tutions where id=/*???*/ 59615)) AND NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy')) <= (SELECT NVL(valid_date_to,to_date('22.12.2999','dd.mm.yyyy'))FROM tutions where id= /*???*/ 59615) AND trunc(valid_date_from) >=(SELECT trunc(valid_date_from)FROM tutions where id= /*???*/ 59615) ;
The result
ID HIN_ID NAME CODE VALID_DATE_TO VALID_DATE
50512 59564 RE YOU 01 07.06.2013 16:32:15 07.06.2013 16:33:28 50513 59564 TT2 02 07.06.2013 16:33:23 07.06.2013 16:33:28 50515 59564 TT2 02 07.06.2013 16:33:28 07.06.2013 16:34:42 50516 59564 STEM 03 07.06.2013 16:34:37 07.06.2013 16:34:42 VALID_DATE_TO & VALID_DATE_FROM information AND
07.06.2013 16:34:42 15.07.2013 10:33:23 In this case, I had doubles of the TT2 50513 entry in a statement identifier select main cant use agregate functions are still possible to exclude this result value by changing only the QLRST a WHERE clause (TRUNC must be here)
THANKS FOR ANY ADVICE!
FDA
Try this,
WITH QRSLT AS (SELECT id, hin_id, name, code, valid_date_from, valid_date_to FROM diaries) SELECT * FROM QRSLT A WHERE (A.hin_id = (SELECT NVL (historic_id, id) FROM tutions WHERE id = /*???*/ 59615)) AND NVL (A.valid_date_to, TO_DATE ('22.12.2999', 'dd.mm.yyyy')) <= (SELECT NVL (valid_date_to, TO_DATE ('22.12.2999', 'dd.mm.yyyy')) FROM tutions WHERE id =/*???*/ 59615) AND TRUNC (A.valid_date_from) >= (SELECT TRUNC (valid_date_from) FROM tutions WHERE id = /*???*/ 59615) AND A.valid_date_from = (SELECT MAX (B.valid_date_from) FROM QRSLT B WHERE A.Name = B.Name AND A.Code = B.Code AND A.hin_id = B.hin_id)
-
Case instructions within a Where clause clause
Hello group,
I know this has been asked several times, but I do not enter simply to a tuition assistance box in a WHERE clause. So I need help:
My current WHERE the clause reads:
A16. FULL_DATE between (SELECT (TRUNC (SysDate - 8)) From Dual) and (select (TRUNC (SysDate - 2)) double)
However, I need to 'automate' a bit, based on the current time/day of the month. I need my instruction box to say:
(Case when to_char (sysdate-3, 'mm') <>to_char (sysdate, 'mm')
then the a16. FULL_DATE (between SELECT (trunc (ADD_MONTHS ((LAST_DAY(SysDate-3)),-1)+1) and (SELECT (add_months (trunc(SysDate-2)-1)) of double)))
Of another a16. FULL_DATE between (SELECT trunc (ADD_MONTHS ((LAST_DAY (SysDate)),-1)+1) From Dual) and (select (TRUNC (SysDate - 2)) From Dual)
However, I have an error on "Else". Can someone explain what is the problem and how to fix it? I tried both 'then' and 'Else' syntax and both will run individually. So I'm quite sure that he does not like my CASE statement in general.
In advance, thank you for your help.
Don
I can't tell what your business logic, so here's a simple example of an instruction box in the where clause:
SQL > select *.
2 double
3 where dummy = case when extracted (sysdate months) = 9 then 'W '.
4 Once extracted (sysdate months) = 10 then 'X '.
When 5 extract (month from sysdate) = 11 then 'Y '.
6 else 'Z'
7 end
8;D
-
X -
No output for report of XML editor using CASE/DECODE in a Where Clause
Hello
I have a requirement of the company to modify an existing report that has two input parameters,
-> p_statcode (closed status) which may have values "Y" or "n".
-> p_overdue (flag late), which can have values of "Y" or "n".
The flag late is a column evaluated with O/N values and it is evaluated as follows,
The requirement of user now is that they must be a third option for setting called p_overdue ALL,ONTF_MOD_VAL(NVL ( (TRUNC (SYSDATE) - (TO_DATE (oe_order_lines.attribute18, 'DD-MON-RRRR') + TO_NUMBER (fnd_lookup_values.meaning))), 0 )) overdue_flag
which by the way the output should include records with
p_statcode is p_statcode ELSE is N AND Y OR p_overdue p_overdue is N
In other words records with raising the Y and N for flag late must be returned regardless of the value given to the closed state.
Original where clause contained in the data definition file is as follows,
My modified code is the following,WHERE Closed_Status = nvl(:p_statcode,Closed_Status) AND overdue_flag = nvl(:p_overdue,overdue_flag)
ORWHERE Closed_Status = NVL (:p_statcode, Closed_Status) AND overdue_flag = (CASE WHEN :p_overdue = 'Y' THEN 'Y' WHEN :p_overdue = 'N' THEN 'N' ELSE overdue_flag END)
Both approaches have the same problem.WHERE Closed_Status = NVL (:p_statcode, Closed_Status) AND overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag)
The output is in EXCEL format. The modified query works very well for p_overdue as Y or N but when p_overdue is passed as ALL he returned a blank EXCEL sheet with just exit report column headings.
Any help regarding, why is this the case? What's not in my approach?
Kind regards
Vishalunclear on p_overdue = ALL
P_overdue = ALL on what necessary values?try sth like
WHERE Closed_Status = NVL (:p_statcode, Closed_Status) AND ( overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag) and :p_overdue != 'ALL' or :p_overdue = 'ALL' and (overdue_flag = 'Y' or overdue_flag = 'N') )
for overdue_flag, which has more then 'Y' values of "n".
If overdue_flag that in ('Y', ' don't) thenWHERE Closed_Status = NVL (:p_statcode, Closed_Status) AND ( overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag) and :p_overdue != 'ALL' or :p_overdue = 'ALL' )
-
Setting of outsourcing work is not for a SQL Where clause
Im trying to outsource the WHERE SQL clause of a snapshot data (connecting to Siebel DB) and specify where clause in the run profile that does not work.
Snapshot of research: Select the name of siebel.s_org_ext
Parameter of outsourcing: where_clause_sql
Run the content of the profile:
phase. Phase1.snapshot.clt.where_clause_sql = name = "ABC0009".
#phase. Phase1.snapshot.clt.snapshot_sql = select name from siebel.s_org_ext where name = 'ABC0009 '.
The above parameter retrieves all the records in the table. Below the profile execution retrieves just this record that seems to work fine.
Run the content of the profile:
phase. Phase1.snapshot.clt.snapshot_sql = select name from siebel.s_org_ext where name = 'ABC0009 '.
I want to outsource only where clause as there are many SQL and they are huge to maintain in the run profile.
I have attached a doco with screenshots that will help to understand more.
Hello
You must BE
-Choose "Select table or view" in the table of the snapshot Wizard selection page
&
-Use outsourced where clause
OR
-Choose "SQL" in the snapshot table selection wizard page.
&
-Outsourced use SQL snapshot
You can't mix and match options.
Kind regards
Nick
-
dynamic logic in SQL WHERE clause based on the value of the ELEMENT
Hello
I have a report based on the following SQL query.
Thank youselect dept_no, dept_name, dept_loc from dept where dept_loc = :P1_DEPT_LOC // If P1_DEPT_LOC is not null, I want the WHERE clause and IF P1_DEPT_LOC is null, then I don't need the WHERE clause. // how can I build this logic in same SQL
Deepak
Published by: Deepak_J on March 11, 2010 16:37where: P1_DEPT_LOC IS NULL or dept_loc =: P1_DEPT_LOC
If dept_loc is not null better would be
where dept_loc = coalesce(:P1_DEPT_LOC,dept_loc)
-
case of condition in where clause
Hello
I am a beginner in SQL, but according to my reading of the manual, this syntax should be acceptable. I'm using application express but tested also in Developer SQL and the conclusion that it fails with an error "invalid relational operator", with the line number pointing to the ELSE clause of the condition, but a number of column pointing to white space.
This is a select statement nested, but that shouldn't matter. The fragment in question is:
Select columns
RES
where res.villaid =: P605_VILLAID
and INSTR (: P604_RES_STATES, res.states). = 0
and (CASE: P604_EXCLUDE_ZERO)
WHEN 'Y' THEN ' res.rate > 0'
ELSE ' res.rate > = 0'
END)
and res. DEPARTDATE >: P605_STARTDATE
and res. ARRIVEDATE < =: P605_ENDDATE.
I hope that this puts ok shaped during the validation. The code is looking for bookings within a range of dates (which works very well when the other conditions are discussed), and should only output offset lines (nights) if the user asks for it in the variable of liaison P604_EXCLUDE_ZERO. There are probably other ways to go about this, but I'm too stubborn to renounce it. Well, not yet anyway.
Thanks and greetings
CSselect some columns from res where res.villaid = :p605_villaid and instr (:p604_res_states, res.states) != 0 and sign (res.rate) >= case when :p604_exclude_zero = 'Y' then 1 else 0 end and res.departdate > :p605_startdate and res.arrivedate <= :p605_enddate
-
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
-
Problem with the creation of date range with PL/SQL WHERE clause
Hello, everyone:
I'm unable to develop and the SQL statement to filter records today and seven days back. My condition is as follows:
I think I'm to mess with the (to_char (ALM_OG_ACTIVITY_DATE, ' mm/dd/yyyy ' ")) statement.from wsualumni.wsu_online_giving_table --where ALM_OG_ACTIVITY_DATE >= ALM_OG_ACTIVITY_DATE - 7 where ALM_OG_ACTIVITY_DATE >= SYSDATE - 7 and ALM_OG_CAMPAIGN_CODE = 'MED' OR ALM_OG_CAMPAIGN_CODE = 'MED1';
The actual code is below to:
Resultsset serveroutput ON SIZE 1000000 set heading off set feedback off set trimspool off set echo off set pagesize 0 DECLARE v_data_line_hdr varchar2(1000); v_data_file varchar2(80); v_sch_code varchar2(10); v_instance_name varchar2(10); ws_path payroll.pybutfl.pybutfl_utl_file_path%TYPE; v_data_line VARCHAR2 (4000) := NULL; fhandle_o UTL_FILE.file_type; v_line_count NUMBER := 0; v_selected_count NUMBER := 0; v_error_count NUMBER := 0; v_written_count NUMBER := 0; v_error_text VARCHAR2 (50) := ' Unable to write the line. '; v_errm VARCHAR2 (255); v_sqlerrm VARCHAR2 (255); CURSOR C1 IS select RTRIM ( ALM_OG_ID ||'|'|| NULL ||'|'|| (to_char(ALM_OG_AMOUNT, '999,999.99')) ||'|'|| 'Cash' ||'|'|| 'Credit Card' ||'|'|| (to_char(ALM_OG_ACTIVITY_DATE, 'mm/dd/yyyy')) ||'|'|| ALM_OG_ACCI_CODE ||'|'|| 'On-Line Giving' ||'|'|| 'On-Line giving' ||'|'|| ALM_OG_HONOR_MEM_NAME ||'|'|| NULL ||'|'|| 'Do not post' ||'|'|| 'StandardThankYou' ||'|'|| 'Not Acknowledged' ||'|'|| 'Do not receipt' ||'|'|| NULL ||'|'|| 'Banner Gift Number' ||'|'|| ALM_OG_BANNER_GIFT_NO ||'.'|| ALM_OG_ACCI_CODE ||'|'|| (to_char(ALM_OG_ACTIVITY_DATE, 'mm/dd/yyyy')) ||'|'|| NULL ||'|'|| 'Web ID' ||'|'|| ALM_OG_WEBID ||'|'|| NULL ||'|'|| 'Source' ||'|'|| ALM_OG_CAMPAIGN_CODE ||'|'|| 'On-Line Giving' ) data_line from wsualumni.wsu_online_giving_table --where ALM_OG_ACTIVITY_DATE >= ALM_OG_ACTIVITY_DATE - 7 where ALM_OG_ACTIVITY_DATE >= SYSDATE - 7 and ALM_OG_CAMPAIGN_CODE = 'MED' OR ALM_OG_CAMPAIGN_CODE = 'MED1'; CURSOR C2 IS select RTRIM( 'ConsID' ||'|'|| 'GFImpID' ||'|'|| 'GFTAmt' ||'|'|| 'GFType' ||'|'|| 'GFPayMeth' ||'|'|| 'GFDate' ||'|'|| 'FundID' ||'|'|| 'CAMPID' ||'|'|| 'GFAppeal' ||'|'|| 'GfRef' ||'|'|| 'GfPostDate' ||'|'|| 'GfPostStatus' ||'|'|| 'GfltrCode' ||'|'|| 'GfAck' ||'|'|| 'GfRcpt' ||'|'|| 'GfAttrlmpID00' ||'|'|| 'GfAttrCat00' ||'|'|| 'GfAttrdesc00' ||'|'|| 'GfAttrDate00' ||'|'|| 'GfAttrlmpD01' ||'|'|| 'GfAttrCat01' ||'|'|| 'GfAttrdesc01' ||'|'|| 'GfAttrlmpID02' ||'|'|| 'GfAttrCat02' ||'|'|| 'GfAttrdesc02' ||'|'|| 'GfSubType' ) line_header from DUAL; /**********************************************************************/ /* Main Program Processing */ /**********************************************************************/ BEGIN DBMS_OUTPUT.put_line ('Program Started in wsualumni.wsu_online_giving_online'); IF UTL_FILE.is_open (fhandle_o) THEN UTL_FILE.fclose (fhandle_o); END IF; /* Name The File Here */ v_data_file := ('MED_SCH_' || TO_CHAR(sysdate, 'dd-MON-yyyy') || '_OG_DATA.txt'); SELECT RTRIM (pybutfl_utl_file_path) INTO ws_path FROM payroll.pybutfl; fhandle_o := UTL_FILE.fopen (ws_path, v_data_file, 'w'); DBMS_OUTPUT.put_line ('UTLFILE file for this run is: ' || ws_path||'/'||v_data_file); v_written_count := 0; FOR c2_rec IN C2 LOOP BEGIN v_selected_count := v_selected_count + 1; v_data_line_hdr := rtrim(c2_rec.line_header); UTL_FILE.put_line (fhandle_o, v_data_line_hdr); v_written_count := v_written_count + 1; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line (v_error_text); v_error_count := v_error_count + 1; END; END LOOP; FOR c1_rec IN C1 LOOP BEGIN v_selected_count := v_selected_count + 1; v_data_line := rtrim(c1_rec.data_line); UTL_FILE.put_line (fhandle_o, v_data_line); v_written_count := v_written_count + 1; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line (v_error_text); v_error_count := v_error_count + 1; END; END LOOP; DBMS_OUTPUT.put_line ('Number of Records Selected: ' || v_selected_count); DBMS_OUTPUT.put_line ('Number of Records Written: ' || v_written_count); IF UTL_FILE.is_open (fhandle_o) THEN UTL_FILE.fclose (fhandle_o); END IF; END; /
ConsID|GFImpID|GFTAmt|GFType|GFPayMeth|GFDate|FundID|CAMPID|GFAppeal|GfRef|GfPostDate|GfPostStatus|GfltrCode|GfAck|GfRcpt|GfAttrlmpID00|GfAttrCat00|GfAttrdesc00|GfAttrDate00|GfAttrlmpD01|GfAttrCat01|GfAttrdesc01|GfAttrlmpID02|GfAttrCat02|GfAttrdesc02|GfSubType 000013505|| 20.00|Cash|Credit Card|06/22/2009|221686|On-Line Giving|On-Line giving|||Do not post|StandardThankYou|Not Acknowledged|Do not receipt||Banner Gift Number|1179534.221686|06/22/2009||Web ID|000013505||Source|MED|On-Line Giving 000013505|| 20.00|Cash|Credit Card|06/22/2009|770830|On-Line Giving|On-Line giving|||Do not post|StandardThankYou|Not Acknowledged|Do not receipt||Banner Gift Number|1179534.770830|06/22/2009||Web ID|000013505||Source|MED|On-Line Giving
Hello
The problem is due to the "OR" condition (I did not pay attention to it earlier).
Because of this condition, your query is given beyond 7 days recovery. You need to rewrite the code as:
ALM_OG_CAMPAIGN_CODE in ('MED', 'MED1')
Instead of
and ALM_OG_CAMPAIGN_CODE = 'MED' OR ALM_OG_CAMPAIGN_CODE = 'MED1';
This will do the magic for you.
Concerning
Asif Momen
http://momendba.blogspot.com -
For UNION in VOImpl SQL WHERE clause
Hey gurus,
I need the ability to add a condition to VOImpl to user_id for two queries in a UNION statement. However, setWhereClause only adds condition at the end of the query. Any suggestions? I tried to make a selection online and could not because of the 'double '.
Thank you
-Scott
Select "Sys" x double where exists)
Select responsibility_name in the fur of fnd_user_responsibility,
fnd_responsibility_tl frt
When user_id = 16448
and frt.responsibility_id = fur.responsibility_id
and frt.responsibility_name = "system administrator")
Union
Select "NoSys" x double where does not exist)
Select responsibility_name in the fur of fnd_user_responsibility,
fnd_responsibility_tl frt
When user_id = 16448
and frt.responsibility_id = fur.responsibility_id
and frt.responsibility_name = "system administrator")You can have the condition at the request of origin itself and in the VOImpl, just switch the setting.
select 'Sys' x from dual where exists ( select responsibility_name from fnd_user_responsibility fur, fnd_responsibility_tl frt where user_id = :1 and frt.responsibility_id = fur.responsibility_id and frt.responsibility_name = 'System Administrator') union select 'NoSys' x from dual where not exists ( select responsibility_name from fnd_user_responsibility fur, fnd_responsibility_tl frt where user_id = :2 and frt.responsibility_id = fur.responsibility_id and frt.responsibility_name = 'System Administrator')
See you soon
Ganesh -
using case when statement or decode unfavorable in where clause
Hi the gems...
I have a problem in the following query...
I try to use when case statement in where clause of a select query.
Select cr.customer_name. ' - ' || CR.customer_number as cust_name,
CR. Salary salary
of customer_details cr
where (case when ' > ' = ' > ' then ' cr.salary > 5000')
When ' > ' = ' < ' then ' cr.salary < 5000'
When ' > ' = '=' and then 'cr.salary = 5000'
Another null
(end);
the expression in the when clause of the statement of the case, when comes from HQ and according to the choice I have to make the where clause.
That is why, for the execution of the query, I put ' > ' in this place.
If the original query will look like this (for reference):
Select cr.customer_name. ' - ' || CR.customer_number as cust_name,
CR. Salary salary
of customer_details cr
where (case when variable = ' > ' then ' cr.salary > 5000')
When the variable = ' < ' then ' cr.salary < 5000'
When the variable = '=' and then 'cr.salary = 5000'
Another null
(end);
so, in a real case, if the user selects ' > ' then the filter will be ' where cr.salary > 5000.
If the user selects ' < ' then the filter will be ' where cr.salary < 5000.
If the user selects '=', then the filter will be 'where cr.salary = 5000 '.
but I get the error "ORA 00920:invalid relational operator.
Help, please... Thanks in advance...Hello
select cr.customer_name || ' - ' ||cr.customer_number as cust_name, cr.salary as salary from customer_details cr where ( v_variable = 'bigger' and cr.salary > 5000 ) or ( v_variable = 'less' and cr.salary < 5000 ) or ( v_variable = 'eq' and cr.salary = 5000 )
Published by: user6806750 on 22.12.2011 14:56
For some reason that I can't write in sql "<', '="">", "=".',>
-
Tuning - using the CASE statement in the WHERE clause of the query
Hi all
My request has been changed to use a CASE statement in the WHERE clause to examine the data to some columns based on a parameter value. This modified request is made a full table and constantly running scan. Please suggest what can be done to improve its performance:
Query:
Description of the table:SELECT LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))) AS summary_date, os.acctnum, os.avieworigin_refid, COUNT(1) cnt_articleview, SUM(NVL(autocompletedterm,0)) cnt_autocompletedterm FROM TABLE1 os WHERE os.acctnum IS NOT NULL AND os.avieworigin_refid IS NOT NULL AND os.requestdatetime IS NOT NULL AND UPPER(os.success_ind) = 'S' AND CASE WHEN Param_ValueToCheck = 'FULL' AND get_date_timestamp(os.requestdatetime) BETWEEN TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') THEN 1 WHEN Param_ValueToCheck = 'INCR' AND os.entry_createddate BETWEEN TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') THEN 1 END = 1 AND CASE WHEN Param_ValueToCheck = 'FULL' AND os.entry_CreatedDate BETWEEN TO_DATE('01-APR-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND TO_DATE('07-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') THEN 1 WHEN Param_ValueToCheck = 'INCR' THEN 1 END = 1 GROUP BY LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))), os.acctnum,os.avieworigin_refid;
(Number of lines: approx. > amount 600 000 000)
Explain PlanName Null Type ------------------------------ -------- ------------ ARTICLEID NOT NULL NUMBER(20) USERKEY NUMBER(10) AVIEWORIGIN_REFID VARCHAR2(10) SUCCESS_IND VARCHAR2(2) ENTRY_CREATEDDATE DATE CREATED_BY VARCHAR2(10) FILENUMBER NUMBER(10) LINENUMBER NUMBER(10) ACCTNUM VARCHAR2(10) AUTOCOMPLETEDTERM NUMBER(2) REQUESTDATETIME VARCHAR2(19)
Published by: Chaitanya on June 9, 2011 02:44SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Plan hash value: 2224314832 ---------------------------------------------------------------------------------------------------------- | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop | ---------------------------------------------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 590 | 33040 | 2501K (1)| 08:20:15 | | | | 1 | HASH GROUP BY | | 590 | 33040 | 2501K (1)| 08:20:15 | | | | 2 | PARTITION RANGE ALL| | 590 | 33040 | 2501K (1)| 08:20:15 | 1 |1048575| |* 3 | TABLE ACCESS FULL | TABLE1 | 590 | 33040 | 2501K (1)| 08:20:15 | 1 |1048575| ---------------------------------------------------------------------------------------------------------- PLAN_TABLE_OUTPUT ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Predicate Information (identified by operation id): --------------------------------------------------- 3 - filter(UPPER("OS"."SUCCESS_IND")='S' AND CASE WHEN ('FULL'='FULL' AND "OS"."ENTRY_CREATEDDATE">=TO_DATE(' 2011-04-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "OS"."ENTRY_CREATEDDATE"<=TO_DATE(' 2011-06-07 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 WHEN 'FULL'='INCR' THEN 1 END =1 AND "OS"."REQUESTDATETIME" IS NOT NULL AND CASE WHEN ('FULL'='FULL' AND "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")>=TO_DATE(' 2011-05-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")<=TO_DATE(' 2011-05-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 WHEN ('FULL'='INCR' AND "OS"."ENTRY_CREATEDDATE">=TO_DATE(' 2011-05-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "OS"."ENTRY_CREATEDDATE"<=TO_DATE(' PLAN_TABLE_OUTPUT ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 2011-05-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 END =1 AND "OS"."ACCTNUM" IS NOT NULL AND "OS"."AVIEWORIGIN_REFID" IS NOT NULL)
Published by: Chaitanya on June 9, 2011 02:47When it is executed individually, MERGE LOGIC 1 and LOGIC of MERGE 2 take about ten for a daterange of 30 days data.
BUT FULL is to get the scores of APR - JUN, INCR becomes partitions for MAY so not both 30 days.
Are compare us like with like? -
Case statement in a WHERE clause
Gurus,
Im trying to avoid Union of several select statements using a CASE inside a WHERE clause. When the parameter is defined as "What's new" it is advisable to use a code and for "Update Items" another condition.
Having a problem with the following... I know that BOX in WHEREs instructions are allowed only can not make it work for this one.
Points for correct and helpful answers!and case when 'New Items' = 'xxx' --p_item_status then msi.creation_date = msi.last_update_date when 'Updated Items' = 'bbb' --p_item_status then msi.creation_date != msi.last_update_date else 1=1 end;
Published by: sreese on March 27, 2012 17:51Hello
The great thing about CASE expressions, is that they allow you to use a login IF-THEN-ELSE in the clause SELECT, the ORDER BY clause or anywhere else. The WHERE clause has its own way to IF-THEN-ELSE logic, so even if you can use a CASE expression in a clause WHERRE, it usually does not help anything. You can do somehting like this:
WHERE ( :p_item_status = 'New Items' AND msi.creation_date = msi.last_update_date ) OR ( :p_item_status = 'Updated Items' AND msi.creation_date != msi.last_update_date ) OR ( :p_item_status NOT IN ( 'New Items' , 'Updated Items' ) )
This guess: p_item_status is not NULL.
If: p_item_status can be NULL, and you want to include all the lines where it is, and then change the last condition toOR ( NVL (:p_item_status, 'OK') NOT IN ( 'New Items' , 'Updated Items' ) )
I hope that answers your question.
If not, post a small example of data (CREATE TABLE and INSERT, only relevant columns instructions), some values of the parameter and the expected results of these data for each value of the parameter.
Explain, using specific examples, how you get these results from these data.
Always tell what version of Oracle you are using. -
Statement UPDATE of SQL TIP about WHERE CLAUSE
(1) Oracle does support SQL UPDATE statement of SUSPICION for WHERE CLAUSE
(2) if so, then please give example.
Thank you.Hello
Yes, it is possible to use the "tips" in the Update statement
Sake example
Update
/ * + rowid * /.
tableX
Set char_date = '19' | char_date
where nvl (length (char_date), 0) = 6
and rowid between chartorowid ('000927.0000.0008')
and chartorowid('000A3F.) FFFF.0008');http://Stanford.edu/dept/ITSS/docs/Oracle/10G/server.101/b10752/hintsref.htm#27647
-Pavan Kumar N
-
Using a CASE statement in 'IN' where clause clause
Hello
I have a form that users see after they connect with a few items and they type or select values based on the element type. All reports in the application use these values of PAGE 1 in where clause to filter the lines.
One of these question is "Quarter". I have a group of radio buttons on the PAGE 1 on the P1_QTR point.
I need to provide users a way to take the last 4, last 3, last 2 or current quarter and I need to dynamically build a clause WHERE the interactive report based on the selection in the form.
I am trying to use the CASE as shown below and get the syntax error.
AND QTR to (when BOX: P1_QTR = 'CURRENT' then ("T4"))
When: P1_QTR = "LAST" then ("Q3")
When: P1_QTR = 'LAST TWO' then ('Q3, "Q4")
When: P1_QTR = 'LAST THREE' then ("Q2", "Q3,' T4 ')
another ("T1", "T2", "Q3,' T4 ')
END)
How can I achieve this?
Following a simple logic, try
and QTR to
(
Select 'T4' double where: P1_QTR <> 'LAST '.
Union of all the
Select 'Q3' to double where: P1_QTR <> "in PROCESS".
Union of all the
Select "Q2" double where: P1_QTR not in ('CURRENT', 'LAST', "LAST TWO")
Union of all the
Select "Q1" double where: P1_QTR not in ('CURRENT', 'LAST', 'LAST TWO', 'THREE LATEST')
)
Maybe you are looking for
-
I installed Windows Live Mail, but cannot uninstall Windows Mail. It isn't in my programs/uninstall. Every email that comes in my new Windows Live Mail also comes in my old Windows Mail. Therefore, I must remove two programs. I have Vista.
-
Update to the blackBerry OS 10 10.2.1.537 "profile Issues.
The new OS is awesome! However, first of all, as I am constantly change my silent profiles and vibrate. You know in and out of meetings, and phone calls icon is crossed out. If I choose the, a notification appears and indicates: and I quote: ' your p
-
Can someone tell me what I need to download to get the latest version of the AnyConnect client to install on a windows system? I tried searching the AnyConnect client out of the download page, and everything I tried not did me not a customer. Not sur
-
Problem with "Orchestrator register in the register of vRealize automation components"
Hi guys,.I had a problem mind save my external Orchestrator in the registry of the vCAC component.The workflow always says: is NOTand the message in the newspapers wrote: 1 (workflow: registry Orchestrator in vRealize component registry Automation /R
-
I can not download because I get error kernel32.dll
Hi I am trying to download creative cloud on my desktop but it won't install gives me an error kernel32.dllPlease can someone help me