Using Case Statement in Where Clause
Hello All,
I wish to conditionally use different columns for retrieving unique row. This will be dependent upon a parameter passed to the Function/Procedure.
The SQL framed looks as below:
+select *+
from Test_Table
where column_1 = <some_value>
and case when p_call_location = 'A' then column_2 like '%ABC%'
when p_call_location = 'B' then column_2 Not Like '%ABC%'
when p_call_location = 'C' then column_3 like '%EFG%'
when p_call_location = 'D' then column_3 like '%IJKL%'
END;
However, I am not sure if this works, as I am getting a Missing Right Paranthesis error. Major hinderance is the depedency on multiple columns, which would need to be referred for particular scenario.
Can somebody please help me with an example or a skeleton of how a query should be formed?
Appreciate an early reply!!!
HI,
i think this may solve your issue...get back to me if u have any qry's on this.
CREATE TABLE Test_Table
(p_call_location VARCHAR2(10),
COLUMN_1 VARCHAR2(20),
COLUMN_2 VARCHAR2(20),
COLUMN_3 VARCHAR2(20))
INSERT INTO Test_Table VALUES('A','COMNVAL','ABC_PER','XXXX');
INSERT INTO Test_Table VALUES('A','COMNVAL','PER','XXXX');
INSERT INTO Test_Table VALUES('B','COMNVAL','ABC_PER','XXXX');
INSERT INTO Test_Table VALUES('B','COMNVAL','PER','XXXX');
INSERT INTO Test_Table VALUES('C','COMNVAL','ABC_PER','EFG_XXXX');
INSERT INTO Test_Table VALUES('C','COMNVAL','ABC_PER','XXXX');
INSERT INTO Test_Table VALUES('D','COMNVAL','ABC_PER','EFG_XXXX_IJKL');
INSERT INTO Test_Table VALUES('D','COMNVAL','ABC_PER','GGG_XXXX');
SELECT * FROM Test_Table WHERE ROWID IN (
select case when p_call_location = 'A' AND column_2 like '%ABC%' THEN ROWID
when p_call_location = 'B' AND column_2 Not Like '%ABC%' THEN ROWID
when p_call_location = 'C' AND column_3 like '%EFG%' THEN ROWID
when p_call_location = 'D' AND column_3 like '%IJKL%' THEN ROWID
END AS KK
from Test_Table
where column_1 = 'COMNVAL');
even u can use the below qry also
select *
from test_table
where column_1 = 'COMNVAL'
and (case when p_call_location = 'A' and column_2 like '%ABC%' then 'VALID'
when p_call_location = 'B' and column_2 Not Like '%ABC%' then 'VALID'
when p_call_location = 'C' and column_3 like '%EFG%' then 'VALID'
when p_call_location = 'D' and column_3 like '%IJKL%' then 'VALID'
else 'INVALID'
END) = 'VALID';
thanks
prasuna.
Edited by: user13820845 on Feb 21, 2011 10:25 PM
Similar Messages
-
Case statement in where clause ??
Hello gurus,
Can we use case statements in where clause ?? Any example will be great!
And also i would like to know, besides CASE and DECODE statements, Is there any way we can use IF ELSE statements in SELECT clause or in WHERE clause ?
Thank you!!Hi,
user642297 wrote:
Hoek,
Thanks for the reply
Whatever you return from 'then' should match your criteria.I didnt get this part...can you elaborate this part ?? Thank you!!Remember what a CASE expression does: it returns a single value in one of the SQL data types (or NULL).
You're probably familiar with conditions such as
WHERE col = 1Inthe example above, col could be replaced by any kind of expression: a function call, and operation (such as "d * 24") or a CASE expression, which is exactly what Hoek posted:
where case
when col = 6 then 1
when col = 9 then 1
end = 1;I think what Hoek meant about mnatching was this: since the CASE expression is being compared to a NUMBER, then every THEN clause (as well as the ELSE, if there is one) should return the same data type. You can't have one THEN clause return a NUMBER, and another one in the same CASE expression return a DATE, like this:
where case
when col = 6 then 1
when col = 9 then SYSDATE -- WRONG! Raises ORA-00932: inconsistent datatypes
end = 1;
By the way, it's rare when a CASE expression really helps in a WHERE clause. CASE is great for doing conitional stuff in places where you otherwise can't (in the ORDER BY clause, for example), but the WHERE clause was designed for conditions.
Hoek was just trying to give a simple example. If you really wanted those results, it would be simpler to say:
where col = 6
or col = 9and simpler still to say
where col IN (6, 9) -
How to use CASE stmt in Where clause
Hi,
How to use CASE stmt in WHERE clause?. I need the code. Please send me as early as possible..........Hi,
1004977 wrote:
Hi,
How to use CASE stmt in WHERE clause?. There's no difference between how a CASE expression is used in a WHERE clause, and how it is used in any other clause. CASE ... END always returns a single scalar value, and it can be used almost anywere a single scalar expression (such as a column, a literal, a single-row function, a + operation, ...) can be used.
CASE expressions aren't needed in WHERE clauses very much. The reason CASE expressions are so useful is that they allow you to do IF-THEN-ELSE logic anywhere in SQL. The WHERE clause already allows you to do IF-THEN-ELSE logic, usually in a more convenient way.
I need the code.So do the peple who want t help you. Post a query where you'd like to use a CASE expression in the WHERE clause. Post CREATE TABLE and INSERT statements for any tables used unless they are commonly available, such as scott.emp). Also, post the results you want from that sample data, and explain how you get those resuts from that data.
See the forum FAQ {message:id=9360002}
Please send me as early as possible..........As mentioned bfore, that's rude. It's also self-defeating. Nobody will refuse to help you because you don't appear pushy enough, but some people will refuse to help you if you appear too pushy. -
Case statement within where clause
How can i write a case statement within Where clause of SQL statement.
Ex:
If sysdate is less than Dec 31 of 2009 then run the query for 2009 else run the query for 2010.
belwo query is not working. Please let me know how can i write a case statement within where clause.
Select * from table
where
Case
when to_char(sysdate,'yyyymmdd')<=20091231 then tax_year=2009
else tax_year=2010
EndHi,
You can get the results you want like this:
Select *
from table
where tax_year = Case
when to_char(sysdate,'yyyymmdd') <= 20091231
then 2009
else 2010
End
;A CASE expression returns a single value in one of the SQL data types, such as a NUMBER, VARCHAR2 or DATE. There is no boolean type in SQL. -
How to use a case statement in where clause
Hi All,
I have a requirement which is to bring all the claims that are created in the last month.So, i wrote a query something like this
select * from claims
where
(Month(ClaimOpenDate) = Month(Getdate())-1 and year(claimopendate) = year(getDate()))
which would give me any new claims created in last month of current year, but this condition fails if we are in the first month of a new year( lets say if we are in 2016 jan then month(getdate())-1 would be 0 and year(getdate()) would be 2016 so we dont
find any records where year is 2016 and month is 0 for claimopen).
So, i would like to use a case statament or something which can help me get around this one.
Can someone please help me with any suggestions?
ThanksHi Jason,
Thanks a lot for your help. This is what exactly i am looking for but i just gave a sample query above below is my original query
select
row_number() over (order by [ClaimNumber]) as DataElementName
,c.PolicyNumber as PolicyNum
, c.FirstName as CustNameF
,c.LastName as CustNameL
,c.PolicyForm as PolType
,'Homesite' as Company
,[ClaimNumber] as ClaimNum
,E.office as Ofc
,e.Supervisior_FullName as Team
, RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FORepF
, case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FORepL
,e.AdjusterID as RepC -- not sure
,CONVERT ( varchar,c.LossDate ,101) as DOL
,convert (varchar,c.ClaimOpenDate,101) as DOR
,rtrim(c.Loss_State) as LossSt
,c.Loss_ZipCode as LossZIP
,c.Loss_City as LossCity
,c.LossType as FOL
,'' as PR
,'' as PRNum
,1 as FeaNum
,'HO' as FeaType
,case when rtrim(c.claimStatus)= 'Closed' then 'Closed' else 'Open' end as FeaStat
,'' as FeaOpen
,'' as FeaClosed
,s.PaymentIndemnityAmount as PaidAmt
,s.ReserveIndemnityAmount as Reserve
,'' as Sub
,'' as Sal
,'' as FeatOwnOfc
,e.Supervisior_FullName as FeatOwnTeam
,RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FeatOwnRepF
,case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FeatOwnRepL
,e.AdjusterID as FeatOwnRepCode
,NULL AS Description --not sure
from [Stg].[HS_DW_RV_Claims] c
inner join [dbo].[Claims_Primary_Adjuster] a on a.CLAIM_NUMBER = c.ClaimNumber
inner join [dbo].[vw_Adjuster] e on e.adjuster_Name = a.primary_ADJUSTER
left outer join [Stg].[HS_DW_LossClaimSummary] s on c.ClaimKey=s.ClaimKey
where c.LoadSource = 'CMS'
and
(s.PaymentIndemnityAmount <>0 or s.PaymentExpenseAmount <>0)
and
ClaimOpenDate BETWEEN DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP) -1, 0) AND DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP), 0)
UNION ALL
select
row_number() over (order by [ClaimNumber]) as DataElementName
,c.PolicyNumber as PolicyNum
, c.FirstName as CustNameF
,c.LastName as CustNameL
,c.PolicyForm as PolType
,'Homesite' as Company
,[ClaimNumber] as ClaimNum
,E.office as Ofc
,e.Supervisior_FullName as Team
, RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FORepF
, case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FORepL
,e.AdjusterID as RepC -- not sure
,CONVERT ( varchar,c.LossDate ,101) as DOL
,convert (varchar,c.ClaimOpenDate,101) as DOR
,rtrim(c.Loss_State) as LossSt
,c.Loss_ZipCode as LossZIP
,c.Loss_City as LossCity
,c.LossType as FOL
,'' as PR
,'' as PRNum
,1 as FeaNum
,'HO' as FeaType
,case when rtrim(c.claimStatus)= 'Closed' then 'Closed' else 'Open' end as FeaStat
,'' as FeaOpen
,'' as FeaClosed
,s.PaymentIndemnityAmount as PaidAmt
,s.ReserveIndemnityAmount as Reserve
,'' as Sub
,'' as Sal
,'' as FeatOwnOfc
,e.Supervisior_FullName as FeatOwnTeam
,RIGHT(e.adjuster_Name ,LEN(e.adjuster_Name)- charindex(',' ,e.adjuster_Name)) as FeatOwnRepF
,case when charindex(',' ,e.adjuster_Name) <> 0 then left(e.adjuster_Name,charindex(',' ,e.adjuster_Name)-1) else e.adjuster_Name end as FeatOwnRepL
,e.AdjusterID as FeatOwnRepCode
,DESCRIPTION --not sure
from Stg.IG_Document D
inner join [Stg].[HS_DW_RV_Claims] c on D.PARENTREF = C.ClaimNumber
inner join [dbo].[Claims_Primary_Adjuster] a on a.CLAIM_NUMBER = c.ClaimNumber
inner join [dbo].[vw_Adjuster] e on e.adjuster_Name = a.primary_ADJUSTER
left outer join [Stg].[HS_DW_LossClaimSummary] s on c.ClaimKey=s.ClaimKey
where c.LoadSource = 'CMS'
and
DESCRIPTION like '%Denial Letter%'
and
ClaimOpenDate BETWEEN DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP) -1, 0) AND DATEADD(mm, DATEDIFF(mm, 0, CURRENT_TIMESTAMP), 0)
So if i use your logic in the end for both the where clauses its been more than 10 minutes and the query is still running however if i use my old method it doesnt even take a second. Looks like its affecting the execution plan. Any suggestions to get around
this one please?
Thanks -
Using :case when in where clause
Hello,
I need some help with using of case statement in a where clause
Table that contains info about employees taking some coursework:
Class (values could be SAP, ORACLE, JAVA)
Code (if Class is SAP then CODE is not null; if class is any other CODE is NULL)
Start Date (date they began class not null)
End Date (date then ended the class - could be null)
Employee Level(numbers from one through five)
I need a single LOV in forms that should show Employee_Level for input class,code,date.
How to do this?
I started off with this but get 'missing statement error'
select distinct employee_level from e_course
where (
case when &class='SAP' then code ='1' and start_date > to_date('20000101','YYYYMMDD') and
end_date < to_date('20000101','YYYYMMDD')
else
null
end) order by employee_level;ThanksHi,
user469956 wrote:
But all these examples have only one condition for each case.Depending on how you count, all WHERE clauses have only one condition.
I see an example in that thread that has 6 atomic conditions, linked by AND and OR.
I need to check date & code. This is what is causing the error.Why do you want to use a CASE statement?
Why can't you put all your conditions directly iinto a WHERE clause, soemthing like this:
WHERE ( &class='SAP'
AND code ='1'
OR ( start_date > to_date('20000101','YYYYMMDD')
AND end_date < to_date('20000101','YYYYMMDD')
)I said "something like this" because I don't know what you really want to do. -
How to use case function in where clause
Hi,
Suppose a table DEMO has columns
DEMO TABLE
user_id
user_name
location
In this table i have 15 users. but out of 15 users i want to use only 5 users for passing as user_name.
then how to achieve the result
1. when i pass the particular 5 user_name in where clause then i should get all the user_name and for other 10 users it will show only the passing user_name.
how to use case functionDo you mean this ?
SQL> var name varchar2(10)
SQL> exec :name := 'ALLEN'
PL/SQL procedure successfully completed.
SQL> select ename from emp where case when :name in ('SMITH','ALLEN') then ename
2 else :name end = ename;
ENAME
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
14 rows selected.
SQL> exec :name := 'SMITH'
PL/SQL procedure successfully completed.
SQL> select ename from emp where case when :name in ('SMITH','ALLEN') then ename
2 else :name end = ename;
ENAME
SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
14 rows selected.
SQL> exec :name := 'BLAKE'
PL/SQL procedure successfully completed.
SQL> select ename from emp where case when :name in ('SMITH','ALLEN') then ename
2 else :name end = ename;
ENAME
BLAKERgds. -
No output for XML Publisher Report using CASE/DECODE in Where Clause
Hi,
I've a business requirement to modify an existing report which has two input parameters,
-> p_statcode (Closed Status) which can have values 'Y' or 'N'
-> p_overdue (Overdue Flag) which can have values 'Y' or 'N'
The Overdue Flag is an evaluated column having values of Y/N and it is evaluated as follows,
ONTF_MOD_VAL(NVL (
(TRUNC (SYSDATE)
- (TO_DATE (oe_order_lines.attribute18,
'DD-MON-RRRR')
+ TO_NUMBER (fnd_lookup_values.meaning))),
0
overdue_flagThe user requirement now is they needs to be a third option for parameter p_overdue called ALL,
passing which the output should include records having
p_statcode is Y ELSE p_statcode is N AND p_overdue is Y OR p_overdue is N
In other words records having both Y and N vlaues for Overdue Flag have to be returned irrespective of the value given to Closed Status.
Original where clause in the Data Definition file is as follows,
WHERE Closed_Status = nvl(:p_statcode,Closed_Status)
AND overdue_flag = nvl(:p_overdue,overdue_flag)My modified code is as follows,
WHERE 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)
OR
WHERE Closed_Status = NVL (:p_statcode, Closed_Status)
AND overdue_flag = DECODE (:p_overdue, 'Y', 'Y', 'N', 'N',overdue_flag)Both approaches have the same problem.
The output is in EXCEL format. The modified query works fine for p_overdue as Y or N but when p_overdue is passed as ALL it returns an empty EXCEL sheet with just the report output column headers.
Any help as to why this is the case ?? What is wrong in my approach ?
Regards,
Vishalnot clear about p_overdue = ALL
which values needed for p_overdue = ALL ?
try smth 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', 'N' values
if overdue_flag only in ('Y','N') then
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'
) -
Case statement with where clause.
I appreciate that there are much simpler ways to run this query but I wondered if anyone else had come across the following -
select distinct
product_table.a,
product_table.b,
product_table.c,
CASE WHEN product_table.c IN ('A','AA') THEN 'AAA'
WHEN product_table.b = 'B' THEN 'BBB'
WHEN product_table.c IN ('C','CC','CCC') THEN 'CCC'
WHEN product_table.b IN ('D','DD') THEN 'DDD'
WHEN product_table.b LIKE 'E%' THEN 'EEE'
WHEN product_table.b LIKE 'F%' THEN 'FFF'
WHEN product_table.b LIKE 'G%' THEN 'GGG'
ELSE 'UNKNOWN' END
from product_table
where
( CASE WHEN product_table.c IN ('A','AA') THEN 'AAA'
WHEN product_table.b = 'B' THEN 'BBB'
WHEN product_table.c IN ('C','CC','CCC') THEN 'CCC'
WHEN product_table.b IN ('D','DD') THEN 'DDD'
WHEN product_table.b LIKE 'E%' THEN 'EEE'
WHEN product_table.b LIKE 'F%' THEN 'FFF'
WHEN product_table.b LIKE 'G%' THEN 'GGG'
ELSE 'UNKNOWN' END) = 'FFF'
when this query runs its as if the where clause = 'FFF' does not exist and all rows are returned.
Thanks, Sarah.Technical questions should be addressed to one of the technical forums. You'll probably find that the folks in the PL/SQL forum (Products | Database | PL/SQL) have some thoughts.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
CFC Best Practise : Using cfif statements in Where Clause
Hi there
Wondering if anyone can advise on the best route to take for handlings cfcs...
I have a function set up as so
<!--- GRAB SONG INFORMATION --->
<cffunction name="getSong" access="remote" output="false" returntype="query" hint="return song information, filtered by user id">
<!---Optional Artist Name Argument--->
<cfargument name="nameArt" type="string" required="false" hint="artist we want to grab song for">
<!---Filter by user ID--->
<cfargument name="idUsr" type="any" required="false" hint="if provided, filter by user id">
<!---Optional Filter by user name--->
<cfargument name="nameUsr" required="false" type="string" hint="if supplied, filter by user name">
<!---Optional song id argument--->
<cfargument name="idSng" required="false" type="numeric" hint="if supplied, grab information for song with this id">
<!--- grab song from database --->
<cfquery name="song" datasource="#APPLICATION.mx#">
// SELECT WHICHEVER FIELDS NECESARRY
SELECT.....
<!---If user id is supplied--->
<cfif isDefined('ARGUMENTS.idUsr')>
<!---Filter results by user id--->
WHERE s.userId = <cfqueryparam value = '#ARGUMENTS.IdUsr#' cfsqltype='CF_SQL_INTEGER'>
</cfif>
<!---If user name is supplied--->
<cfif isDefined('ARGUMENTS.nameUsr')>
<!---Filter results by user id--->
WHERE s.userId = (SELECT iUserID
FROM users
WHERE name = <cfqueryparam value = '#ARGUMENTS.nameUsr#' cfsqltype='CF_SQL_VARCHAR' maxLength="12">)
</cfif>
<cfif isDefined('ARGUMENTS.idSng')>
WHERE s.iSongID = <cfqueryparam value = '#ARGUMENTS.idSng#' cfsqltype='CF_SQL_INTEGER'>
</cfif>
ORDER BY s.iSongID DESC
</cfquery>
<!---Return query output--->
<cfreturn song>
</cffunction>
Now im wondering, is it best to have multiple cfifs in the same function, filtering data dependant on what arguments are supplied, or is it best to seperate the function into seperate functions with different filters, without the cfifs?
Many thanksAlso keep in mind that some of your logic can be done on the database side instead of the CF side:
SELECT myFieldA, myFieldB
FROM myTable
WHERE myFieldA = CASE WHEN isNULL(@MyDBVar,'') = '' THEN myFieldA ELSE @MyDBVar END
Will filter your results matching the field myFieldA against the value of the variable @MyDBVar (if it is passed in). You can also use conditional logic to make larger changes to your database query depending on the DB you are using. -
Evaluation of condition clause in whehe clause using case statement
Hi,
I have a scenario where in I have to evaluate two different conditions based on the parameter value. Is it possible to evaluate the conditiond based on the parameter value with case statement in where clause.
Example:
select A,B,C,D from X,Y,Z
where
cond1 and
cond2 and
case when param='T' then cond3 else cond4 end
Here param is an external parameter passed to the query.
cond3 is something like Y.deptno in(10,30,50,70)
cond4 is something like Y.deptno in (20,40,60,70,80,90)
Your responce will be appriciated.
Regards,
VarmaYou can place the case statement as a condition, however it depends what context you want it in, for example;
this will work:
1* select 1 from dual where (case when 1=1 then 1 end) = 1 and 2=2
QL> /
1
1but this will not;
SQL> select 1 from dual where case when 1=1 then 1 end and 2=2;
select 1 from dual where case when 1=1 then 1 end and 2=2
ERROR at line 1:
ORA-00920: invalid relational operatorSo, if you're expecting the condition to evaluate to a true/false, so if you mean soemthing like
when TRUE, then it won't work!
P; -
CASE Statement in Where Condition with Multi Valued parameter in SSRS
Hi All,
I am little confused while using CASE statement in Where condition in SSRS. Below is my scenario:
SELECT
Logic here
WHERE
Date IN (@Date)AND
(CASE
WHEN NAME LIKE 'ABC%' THEN 'GROUP1'
WHEN ID IN ('123456', '823423','74233784') THEN 'GROUP2'
WHEN ABC_ID IS NULL THEN 'GROUP3'
ELSE 'GROUP4'
END ) IN (@GROUP)
So above query uses WHERE condition with CASE statement from @GROUP parameter. I want to pass this parameter as multi- valued parameter and hence I have used CASE statement IN (@GROUP).
For @Date one dataset will pass the available and default values and
for @GROUP parameters, another dataset will pass the available and default values.
But this is not working as expected. Please suggest me where I am making mistake in the query.
Maruthu | http://sharepoint-works.blogspot.comHi Maruthu,
According to your description, I create a sample report in my local environment. It works as I expected. In your scenario, if the selected values from the Date parameter contains some of the Date field values, the selected values from the GROUP parameter
contains some of GROUPS (‘GROUP1’,’GROUP2’,’GROUP3’,’GROUP4’) and the corresponding when statement is executed , then the dataset returns the corresponding values.
In order to trouble shoot this issue, could you tell us what results are you get and what’s your desired results? If possible, you can post the sample data with sample dataset, then we can make further analysis and help you out.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
Query Tuning - using CASE statement in the WHERE clause - Duplicate Post
Duplicate Post by mistake.
Please check
Query Tuning - using CASE statement in the WHERE clause
Edited by: Chaitanya on Jun 9, 2011 2:45 AM
Edited by: Chaitanya on Jun 9, 2011 2:46 AMDuplicate Post by mistake.
Please check
Query Tuning - using CASE statement in the WHERE clause
Edited by: Chaitanya on Jun 9, 2011 2:45 AM
Edited by: Chaitanya on Jun 9, 2011 2:46 AM -
Using case statement in merge when matched
Hi,
I want to use case statement in the when matched clause of merge statement to ensure that I update only those fields that are undated.
create table TEST1
NAME1 VARCHAR2(25),
NAME2 VARCHAR2(25),
ID NUMBER not null
create table TEST2
ID NUMBER not null,
ID2 NUMBER not null,
NAME1 VARCHAR2(25),
NAME2 VARCHAR2(25)
merge into test1 t1
using
test2 t2
ON (t1.id = t2.id)
when matched
then
case
when t1.name1 != t2.name1
then
update set t1.name1 != t2.name1
when t1.name2 != t2.name2
then
update set t1.name2 != t2.name2
else
null;
end
it does not work and raises invalid sql command. Any idea how can I do that?
Thanks.
Sajid
Edited by: 808255 on Nov 12, 2010 4:22 AMHi
In that case you would have to use multiple statements and you may as well just use UPDATE instead of MERGE. Also, are you sure that you aren't trying to to fix a problem that doesn't actually exist.
Think about where the execution time is going to come from...
I would be tempted to do 1 UPDATE like this...
UPDATE test1 t1
SET (t1.name1,
t1.name2) = (SELECT t2.name1,
t2.name2
FROM test2 t2
WHERE t1.id = t2.id
AND (t1.name1 != t2.name1
OR t1.name2 != t2.name2))If you get specific performance issue with this, then post an explain plan and trace and I'll have a look.
I don't this the cost of the update is going to be as great as you think.
Cheers
Ben -
CASE in a WHERE clause : ORA-00905
Hi everyone,
I am trying to use a CASE in a WHERE clause and I got the error ORA-00905: missing keyword. Here is my code :
SELECT id_reserv,
concat(nom,concat('_',indice)) as nom,
libelle,
num_lot,
resa_keyword1,
resa_keyword2,
resa_keyword3,
resa_keyword4,
date_creation,
comm_creation,
id_util,
actif,
id_env_act,
(SELECT login from utilisateur u where u.id_util=r.id_util) AS nom_util,
(SELECT nom from environnement e where e.id_env=r.id_env_act) AS nom_env,
(SELECT count(*) from reserv_comp rc where rc.id_reserv=r.id_reserv) AS nbComp,
(SELECT count(*) from reserv_modif mc where mc.id_reserv=r.id_reserv) AS nbModif
FROM reservation r
WHERE r.nom NOT LIKE 'RESERV_LOT_%'
AND id_util='1'
AND actif='1'
AND id_env_act>='-1'
AND CASE sansdemande
WHEN true THEN id_reserv not in select id_reserv from demande_livraison where id_env_dep>='-1'
ELSE id_reserv=id_reserv
END
AND nom LIKE '%'
ORDER BY date_creation;
I already looked at the CASE statement and it seems that the syntax is correct, so I'm not sure I can use it in a WHERE clause.
Any help would be nice !
GuichHi,
it should be something like this:
AND CASE
WHEN 'false'='true' THEN (select id_reserv from demande_livraison where id_env_dep>='-1')
ELSE id_reserv
END = id_reserv The subquery should give one row back
But I think it is better to write your query as:
SELECT id_reserv,
concat(nom,concat('_',indice)) as nom,
libelle,
num_lot,
resa_keyword1,
resa_keyword2,
resa_keyword3,
resa_keyword4,
date_creation,
comm_creation,
id_util,
actif,
id_env_act,
(SELECT login from utilisateur u where u.id_util=r.id_util) AS nom_util,
(SELECT nom from environnement e where e.id_env=r.id_env_act) AS nom_env,
(SELECT count(*) from reserv_comp rc where rc.id_reserv=r.id_reserv) AS nbComp,
(SELECT count(*) from reserv_modif mc where mc.id_reserv=r.id_reserv) AS nbModif
FROM reservation r
WHERE r.nom NOT LIKE 'RESERV_LOT_%'
AND id_util='1'
AND actif='1'
AND id_env_act>='-1'
AND
( 'false'='true' and id_reserv not in (select id_reserv from demande_livraison where id_env_dep>='-1')
or
( 'true'= 'true' and id_reserv=id_reserv
AND nom LIKE '%'
ORDER BY date_creation;This coding in SQL something as if a=b then c, else d in the simplest form.
Herald ten Dam
http://htendam.wordpress.com
Maybe you are looking for
-
Transferring VOB files ex Sony Handycam DVD
OK it's my turn. I bought the newer model HD Sony Handycam- you know, the one that likes mini 8cm. DVD discs. Great camera- when I learn how to use it properly. The BIG problem is- how do I transfer the VOB files on the 8cm. DVD disks to iMovie ??? A
-
ASA5505 - The third VLAN on a base license
According to this document (http://www.cisco.com/en/US/docs/security/asa/asa72/asdm52/user/guide/ifcs5505.html) I can make the third VLAN to initiate traffic in one direction as depicted in this diagram This means that although 'Home' cannot communic
-
If your database in Full Recovery mode, can you use Bulk Insert Task to load data
If your database in Full Recovery mode, can you use Bulk Insert Task to load data
-
There is no record in my ZEN neeon 5
Dear Sir i have some problem with my MP3 player recorder. i didn't see the name of '' record" in my recorder now. so when i record a song from outside and open it in my record, it is ok. but when i come to open in computer, i don't see the song i had
-
Hello, I wanted to know how to create DRM hierarchies. I have the DRM document but unable to exactly figure it out. Also, what are the key Blender, Import and Export profile settings/configs. I understand this is a broad question but I am looking for