Formatted search case statement help
Hi all,
I am trying to write a case statement in a formatted search, but am running into an error when I add a condition involving the item code. The code works find with the first WHEN statement involving the customer code $[$4.0.0] however, I receive an internal error when I add the second part involving the item code $[$38.1.1] Please advise.
SELECT
CASE WHEN $[$4.0.0] = 'C00023'
THEN 'E002'
WHEN $[$38.1.1] = 'ItemA'
THEN 'J002'
END
THank you!
Jane
Hi Jane,
Where do you assign this FMS? If it is on the header, the second condition will not work. If it is line level, try change it to $[$38.1.0\].
Thanks,
Gordon
Similar Messages
-
Formatted search - case statement
I am trying to do a formatted search that would set the GL account field on the sales order row based on the first 2 digits of the business partner card code.
SELECT CASE
WHEN $[ORDR.cardcode] like "01%" then '40100-01'
WHEN $[ORDR.cardcode] like "02%" then '40100-02'
WHEN $[ORDR.cardcode] like "03%" then '40100-03'
WHEN $[ORDR.cardcode] like "04%" then '40100-04'
WHEN $[ORDR.cardcode] like "05%" then '40100-05'
WHEN $[ORDR.cardcode] like "06%" then '40100-06'
WHEN $[ORDR.cardcode] like "07%" then '40100-07'
WHEN $[ORDR.cardcode] like "08%" then '40100-08'
WHEN $[ORDR.cardcode] like "09%" then '40100-09'
WHEN $[ORDR.cardcode] like "10%" then '40100-10'
WHEN $[ORDR.cardcode] like "13%" then '40100-13'
else '40100-00'
The above does not work. I am trying to do this and refresh when the itemcode changes or anything on the row level.
Any ideas on what might be wrong?
Thanks in advance for any helpHere is an example :
SELECT CASE
WHEN $[$38.18.0] = 'OPPN1' THEN ($[$38.U_Price.NUMBER]/1.1)
WHEN $[$38.18.0] = 'OPPN2' THEN ($[$38.U_Price.NUMBER]/1.1)
WHEN $[$38.18.0] = 'OPPN3' THEN ($[$38.U_Price.NUMBER])
WHEN $[$38.18.0] = 'OPPN4' THEN ($[$38.U_Price.NUMBER])
WHEN $[$38.18.0] = 'OPPN0' THEN ($[$38.U_Price.NUMBER]) END
I suggest to use
$[$item.column.number/curr/date/0]
instead of
$[ordr.cardcode]
I have a SAP pdf file related to FMS. Let me know if you need it.
Rgds, -
case
when datepart(mm,[SDate]) between '9' and '11' and datepart(mm,[PDate] ) between '9' and '11'
Then 'Q1_'
when datepart(mm,[SDate]) between '12' and '02' and datepart(mm,[PDate] ) between '12' and '02'
Then 'Q2_'
when datepart(mm,[SDate]) between '03' and '05' and datepart(mm,[PDate] ) between '03' and '05'
Then 'Q3_'
when datepart(mm,[SDate]) between '06' and '08' and datepart(mm,[PDate] ) between '06' and '08'
Then 'Q4_'
else 'N/A' end as QTR
from DDA_2015_FSR
Datatype for SDate and Pdate
2014-09-01 00:00:00
I need help with above case statement, When I run the case statement I get 'N/A FSY_2015 ' When I add the following where clause to validate the results. In my table I do have records for all four quarters, Except Q1, all other rows I get 'N/A
FSY_2015 '
Am i missing something? Can someone help me here?
where
datepart(m,[SDate])
between
'12'
and
'02'
and
datepart(m,[PDate]
between
'12'
and
'02'
FMThere is no CASE statement in SQL; it is a CASE expression. Big difference.
Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
The report period table gives a name to a range of dates that is common to the entire enterprise.
CREATE TABLE Something_Report_Periods
(something_report_name CHAR(10) NOT NULL PRIMARY KEY
CHECK (something_report_name LIKE <pattern>),
something_report_start_date DATE NOT NULL,
something_report_end_date DATE NOT NULL,
CONSTRAINT date_ordering
CHECK (something_report_start_date <= something_report_end_date),
etc);
These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Switch Case Statement Help...
Hello,
I am trying to get my pages through Case Statement But...
Can any one Help me.. here is my code..
This is my Buttons Code... My buttons are on 1st Frame of My FLA..
stop();
btn1.addEventListener(MouseEvent.CLICK, varTest);
btn2.addEventListener(MouseEvent.CLICK, varTest2);
function varTest(event:MouseEvent):void
var page = 1;
gotoAndStop(20);
function varTest2(event:MouseEvent):void
var page = 2;
gotoAndStop(20);
and this is my 20th frame code. (here I'm checking variable)
import flash.events.Event;
addEventListener(Event.ENTER_FRAME,checkCaseMe);
function checkCaseMe(event:Event)
switch (page)
case "1" :
info_txt.text = "page1";
break;
case "2" :
info_txt.text = "page1";
break;
default :
info_txt.text = "page00";
When I test the movie.. Error Occured (Scene 1, Layer 'Actions', Frame 21, Line 6 1120: Access of undefined property page. )
Can Anyone help please.. How do I correct this....???
Thanks...You should learn to use the trace() function to help you troubleshoot code yourself. In each of your button functions include:
trace("btn clicked"); // will help you know for sure that the buttons are working
And in frame 20, you should add a trace as well to determine whether you actually get there when you think you don't...
trace("in frame 20");
Lastly, your code for frame 20 is likely not what you need for a couple of reasons...
1) If you think the ENTER_FRAME listener is used to detect/trigger when the timeline enters a frame, that is not what it does. What it does is continually process the function that it calls at the frame rate of the file. It is normally only used when you want to repeatedly trigger some functionality.
2) If you assign number values to the page variable, you do not want to use String values in your cases.
All you should need in frame 20 is...
switch (page)
case 1 :
info_txt.text = "page1";
break;
case 2 :
info_txt.text = "page1";
break;
default :
info_txt.text = "page00"; -
Case statement help needed bit tricky
I have a requirement for a Column Quarters which will idenitfy records based on their service and paid paids.
Output of Column should be
QTR
FSY2015Q1
Our Quarters start like this Q1= 9/1 /2014-11.30.2014 , Q2 12/1/2014 -02/28/2015, Q3: 3/1/2015 - 05/31/2015 Q4:06/01/2015 -08/31/2015.
With the below Case statement records that hit Q1 should be for the FSY upcoming. records in Sept, Oct, November of 2014, would actually be for FSY15Q1 (not FSY14Q1). How can i correct
this ?
case
when datepart(mm, Service_Through_Date ) between '9' and '11' and datepart(mm, c.paid_date ) between '9' and '11'
Then 'Q1 '
when datepart(mm, Service_Through_Date ) in ('01','02', '12' ) and datepart(mm, paid_date ) in ('01','02' , '12' )
Then 'Q2 '
when datepart(mm, Service_Through_Date ) between '03' and '05' and datepart(mm, paid_date ) between '03' and '05'
Then 'Q3 '
when datepart(mm, Service_Through_Date ) between '06' and '08' and datepart(mm, paid_date ) between '06' and '08'
Then 'Q4 '
else ' ' end + ' ' + 'FSY ' + '' + cast(datepart(Year, Service_Through_Date)as char(7)) as QTR
FMYour best bet here is going to be to create a calendar table, which has your quarters in it.
I wrote an article on them here: http://social.technet.microsoft.com/wiki/contents/articles/29260.tsql-calendar-functions-and-tables.aspx.
For your particular scenario you'll need to add a column to the existing code, something like this:
SELECT CASE WHEN DATEPART(MONTH,@date) IN (9,10,11) THEN 'FSY'+RIGHT(YEAR(@date)+1,2)+'Q1'
WHEN DATEPART(MONTH,@date) IN (12) THEN 'FSY'+RIGHT(YEAR(@date)+1,2)+'Q2'
WHEN DATEPART(MONTH,@date) IN (1,2) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q2'
WHEN DATEPART(MONTH,@date) IN (3,4,5) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q3'
WHEN DATEPART(MONTH,@date) IN (6,7,8) THEN 'FSY'+RIGHT(YEAR(@date),2)+'Q4'
END AS fiscalQuarterName
Once you have this column, you can simply join to the calendar table:
SELECT service_through_date, paid_date, sc.fiscalQuarterName, pc.fiscalQuarterName
FROM myTable t
INNER JOIN calendar sc
ON t.service_through_date = c.today
INNER JOIN calendar pc
ON t.paid_date = pc.today
If you can't, or don't want to impliment this, you could solve the issue in your cast statement by moving the year into the CASE, like this:
SELECT CASE WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 9 AND 11 AND DATEPART(MONTH, c.paid_date) BETWEEN 9 AND 11 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date)+1,2)+'Q1'
WHEN DATEPART(MONTH, Service_Through_Date ) = 12 AND DATEPART(MONTH, c.paid_date) = 12 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date)+1,2)+'Q2'
WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 1 AND 2 AND DATEPART(MONTH, paid_date) BETWEEN 1 AND 2 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q2'
WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 3 AND 5 AND DATEPART(MONTH, paid_date) BETWEEN 3 AND 5 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q3'
WHEN DATEPART(MONTH, Service_Through_Date ) BETWEEN 6 AND 8 AND DATEPART(MONTH, paid_date) BETWEEN 6 AND 8 THEN 'FSY'+RIGHT(YEAR(Service_Through_Date),2)+'Q4'
ELSE 'FSY'+RIGHT(YEAR(Service_Through_Date),2)
END
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question. -
Case Statement Help needed [Nested]
Hi all,
I need to write a case statement my requirement is
ENC.EET.40 E_Disposition populated from either “E_ Status” field of HP_Response_table, “File Status” of HP _TTT_Response_Table,
or “E_Status” of DDA_R_Table. If no data in any of these fields, default to “Submitted”
So my case stmt should look like
case when E_Status is null then 'SUBMITTED'
when e_status is null then 'Submitted'
when FileStatus is null then 'Submitted'
Else case when E_status is not null then ............?????????????
else case when
Im Confused.. Can someone help me ?
FMselect ...
coalesce (resp.E_Status, resp2.FileStatus, dda.E_Status, 'Submitted')
from ...
Obviously I have used alias for the respective tables according to your logic. -
Conditional case statement help.!
Hello Forum Members,
I have a table with stores order along with order dates and other information. I have a requirement to write a query to get the nominations from that order's table according to the logic mentioned below.
Nom1 = Initial order date and next order within 7 days from initial order date then its considered as R1
Nom2 = next activity within 7 seven on the same ord_id from its R1 date , this goes on as the order dates increases for same or single ord_no
Final Rn is Count (Rn)
Rn %-- Count(Rn) / Count Distinct ( ord_no ) * 100
Example data output:
ORD_DATE
ORD_ID
1_of_x
2_of_x
3_of_x
4_of_x
5_of_x
6_of_x
Final RnX
Rn%
7/10/2013
10095V1
1
0
0
0
0
0
8/3/2013
10095V1
1
0
0
0
0
0
8/8/2013
10095V1
0
1
0
0
0
0
8/12/2013
10095V1
0
0
1
0
0
0
9/6/2013
10095V1
1
0
0
0
0
0
DDL:
create table xx_ord_noms
ord_no varchar(30),
ord_date date,
ord_id varchar2(30)
Sample Data:
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('07/10/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/03/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/08/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/12/2013','MM/DD/YYYY'), '10091');
INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('09/06/2013','MM/DD/YYYY'), '10091');
commit;
I was planning to doing something like this but I am not getting the logic for R1 .. R7
select ord_no,
ord_date,
ord_id,
prev_dt,
(to_date(ord_date) - to_date(prev_dt)) data_diff,
case
when prev_dt is null or
(to_date(ord_date) - to_date(prev_dt)) < 7 then
'R1'
when (to_date(ord_date) - to_date(prev_dt)) > 7 THEN
'R2'
ELSE
nULL
END
FROM (select a.*,
(SELECT MAX(tmp2.ord_date)
FROM xx_ord_noms tmp2
WHERE a.ord_id = tmp2.ord_id
AND tmp2.ord_date < a.ord_date) prev_dt
from xx_ord_noms a);
Could someone give me advises or suggestions on how we can get the expected output.
Thanks in advance.LAG and LEAD are good when you want to look forward or back a fixed number of rows, but in this case you don't know how far back you'll need to go.
I've got a solution. it calculates the Rn as a number, not a column position, but you can transform that with CASE statements if you want. I did it in two main steps:
First I calculated the Rn by comparing the date of the current and previous row. To do that, I generated a row number using the row_number() analytic function:
select ord_no,
ord_date,
ord_id,
numrow
, Rn
from xx_ord_noms
model
partition by (ord_no)
dimension by (row_number() over (partition by ord_no order by ord_date) numrow)
measures (ord_date, 0 Rn, ord_id )
rules update
rn[1] = 1,
rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1]) < 7 then rn[cv()-1]+1 else 1 end
ORD_NO ORD_DATE ORD_ID NUMROW RN
10091 10-Jul-2013 00:00:00 10091 1 1
10091 03-Aug-2013 00:00:00 10091 2 1
10091 08-Aug-2013 00:00:00 10091 3 2
10091 12-Aug-2013 00:00:00 10091 4 3
10091 06-Sep-2013 00:00:00 10091 5 1
Then I needed to identify all the rows of each series. I defined firstDt as the date of the first item in the series:
firstDt[1] = ord_date[cv()]
firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
With that, the FinalRn is just an analytic max(rn) over (partition by firstDt)
I'm not clear on what R% is. Your descriptions are unclear and I think they're inconsistent.
select ord_no, ord_date, ord_id
, Rn, finalRn, 100*finalRn/totCnt PCT1, 100 * totRn/totCnt PCT2
, totRn
from xx_ord_noms
model
partition by (ord_no)
dimension by (row_number() over (partition by ord_no order by ord_date) numrow)
measures (ord_date, 0 Rn, ord_id, to_date(null) firstDt, 0 finalRn, 0 totRn, 0 totCnt )
rules upsert all
rn[1] = 1
, rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1]) < 7 then rn[cv()-1]+1 else 1 end
, firstDt[1] = ord_date[cv()]
, firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
, finalRn[ANY] = max(rn) over (partition by firstDt)
, totCnt[ANY] = count(*) over()
, totRn[ANY] = count(case when rn = 1 then 1 else null end) over ()
ORD_NO ORD_DATE ORD_ID RN FINALRN PCT1 PCT2 TOTRN
10091 10-Jul-2013 00:00:00 10091 1 1 20 60 3
10091 03-Aug-2013 00:00:00 10091 1 3 60 60 3
10091 08-Aug-2013 00:00:00 10091 2 3 60 60 3
10091 12-Aug-2013 00:00:00 10091 3 3 60 60 3
10091 06-Sep-2013 00:00:00 10091 1 1 20 60 3
Regards,
David -
Hi Gurus,
I have a requirement like this,
I want to extract the service request which closed in last month and opened in the last three months of closing month (close month -3).
When open month is previous month and timestampdiff(tsi_month, open month(close month), openmonth(close month -3) then nbr of SRs.
How do i bring the close month in open month value.
ThanksI am trying to enter the following statement for the above requirment
CASE WHEN "Core"."Close Date"."Close Month" = VALUEOF(PREVIOUS_MONTH) AND TimeStampDiff(SQL_TSI_Month, "Core"."Open Date"."Open Month" = VALUEOF(PREVIOUS_MONTH) , "Core"."Open Date"."Open Month" = VALUEOF(PREVIOUS_MONTH) - 3 ) <= 3 THEN 1 ELSE 0 END
When i say okay, it gives the error
[nQSError: 27002] Near <=>: Syntax error [nQSError: 26012] .
Can anyone help me out.
Thanks -
SQL Case statement Help....
Hi , I have to Compare two columns to see if they are matching or not....and give the count() of overrides if they are not matching/
I have got that with the below SQL:
Count of Overrides =
select count(Case when Col_1 != Col_2 then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
But now i have to look at two columns and get the count()
I have
col_1 and col_2 in table_1 and
col_3 and col_4 in table_2
(I have to compare col_1 with col_2 and...... col_3 with col_4 and if either of them is not matching.... count it as an override
Will the following SQL return correct values?
Count of Overrides =
Select
Count( Case when (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end) Overrides
from table_1, table_2
where table_1.id = table_2.id
Thanks"yes, it can be rewritten as a decode. but why bother?"
Well, although I do like Sy's code better, the decode version does naturally handle NULLs unlike the case.
SQL> WITH t AS (
2 SELECT 1 col_1, 1 col_2, 2 col_3, 2 col_4 FROM dual UNION ALL
3 SELECT 1, 1, 2, 3 FROM dual UNION ALL
4 SELECT 1, 2, 3, 3 FROM dual UNION ALL
5 SELECT null, 1, 2, 2 FROM dual UNION ALL
6 SELECT 1, 1, 2, null FROM dual UNION ALL
7 SELECT 1, 2, 3, 4 FROM dual)
8 SELECT col_1, col_2, col_3, col_4,
9 CASE WHEN (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end Ocase,
10 DECODE(col_1, col_2, DECODE(col_3, col_4, NULL, 1), 1) odecode
11 FROM t;
COL_1 COL_2 COL_3 COL_4 OCASE O
1 1 2 2
1 1 2 3 1 1
1 2 3 3 1 1
1 2 2 1
1 1 2 1
1 2 3 4 1 1John -
CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
제품 : PL/SQL
작성날짜 : 2001-11-13
CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
=======================================================
PURPOSE
아래의 자료는 Case 문에서 oracle 8.1.7과 Oracle 9i의 New Feature로 8.1.7에서는
sqlplus 에서만 가능했고, 9i 부터는 pl/sql 까지 가능하다.
Explanation
1. Oracle 8.1.7 Feature
Oracle 8.1.7 에서 Case 문은 Decode 문과 유사하지만, 기존의 decode 문을 쓰는 것보다
더 많은 확장성과 Logical Power와 좋은 성능을 제공한다. 주로 나이와 같이 category 별로
나눌때 주로 사용하고 Syntex는 아래와 같다.
CASE WHEN <cond1> THEN <v1> WHEN <cond2> THEN <v2> ... [ELSE <vn+1> ] END
각각의 WHEN...THEN 절의 argument 는 255 까지 가능하고 이 Limit를 해결하려면
Oracle 8i Reference를 참조하면 된다.
The maximum number of arguments in a CASE expression is 255, and each
WHEN ... THEN pair counts as two arguments. To avoid exceeding the limit of 128 choices,
you can nest CASE expressions. That is expr1 can itself be a CASE expression.
Case Example : 한 회사의 모든 종업원의 평균 봉급을 계산하는데 봉급이 $2000보다 작은경우
2000으로 계산을 하는 방법이 pl/sql을 대신하여 case function을 사용할 수 있다.
SELECT AVG(CASE when e.sal > 2000 THEN e.sal ELSE 2000 end) FROM emp e;
Case Example : 나이를 column으로 가지고 있는 customer table을 예로 들어보자.
SQL> SELECT
2 SUM(CASE WHEN age BETWEEN 70 AND 79 THEN 1 ELSE 0 END) as "70-79",
3 SUM(CASE WHEN age BETWEEN 80 AND 89 THEN 1 ELSE 0 END) as "80-89",
4 SUM(CASE WHEN age BETWEEN 90 AND 99 THEN 1 ELSE 0 END) as "90-99",
5 SUM(CASE WHEN age > 99 THEN 1 ELSE 0 END) as "100+"
6 FROM customer;
70-79 80-89 90-99 100+
4 2 3 1
1 SELECT
2 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
3 WHEN age BETWEEN 80 and 89 THEN '80-89'
4 WHEN age BETWEEN 90 and 99 THEN '90-99'
5 WHEN age > 99 THEN '100+' END) as age_group,
6 COUNT(*) as age_count
7 FROM customer
8 GROUP BY
9 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
10 WHEN age BETWEEN 80 and 89 THEN '80-89'
11 WHEN age BETWEEN 90 and 99 THEN '90-99'
12* WHEN age > 99 THEN '100+' END)
SQL> /
AGE_G AGE_COUNT
100+ 1
70-79 4
80-89 2
90-99 3
Example
2. Oracle 9i Feature
Oracle 9i부터는 pl/sql에서도 case문을 사용할 수 있으면 이것은
복잡한 if-else 구문을 없애고, C언어의 switch문과 같은 기능을 한다.
아래의 9i pl/sql Sample 및 제약 사항을 보면 아래와 같다.
Sample 1:
A simple example demonstrating the proper syntax for a case
statement
using a character variable as the selector. See the section entitled
'Restrictions' at the end of this article for details on which PLSQL
datatypes may appear as a selector in a case statement or
expression.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
begin
case achar
when 'A' then dbms_output.put_line('The description was Excellent');
when 'B' then dbms_output.put_line('The description was Very Good');
when 'C' then dbms_output.put_line('The description was Good');
when 'D' then dbms_output.put_line('The description was Fair');
when 'F' then dbms_output.put_line('The description was Poor');
else dbms_output.put_line('The description was No such Grade');
end case;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 2:
A simple example demonstrating the proper syntax for a case
expression
using a character variable as the selector. See the section entitled
'Restrictions' at the end of this article for details on which PLSQL
datatypes may appear as a selector in a case statement or
expression.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
description varchar2(20);
begin
description :=
case achar
when 'A' then 'Excellent'
when 'B' then 'Very Good'
when 'C' then 'Good'
when 'D' then 'Fair'
when 'F' then 'Poor'
else 'No such grade'
end;
dbms_output.put_line('The description was ' || description);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
NOTE: The above simple samples demonstrate two subtle differences in the
syntax
required for case statements and expressions.
1) A case STATEMENT is terminated using the 'end case' keywords; a
case
EXPRESSION is terminated using only the 'end' keyword.
2) Each item in a case STATEMENT consists of one or more
statements, each
terminated by a semicolon. Each item in a case expression
consists of
exactly one expression, not terminated by a semicolon.
Sample 3:
Sample 1 demonstrates a simple case statement in which the selector
is
compared for equality with each item in the case statement body.
PL/SQL
also provides a 'searched' case statement as an alternative; rather
than
providing a selector and a list of values, each item in the body of
the
case statement provides its own predicate. This predicate can be any
valid boolean expression, but only one case will be selected.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
begin
case
when achar = 'A' then dbms_output.put_line('The description was
Excellent');
when achar = 'B' then dbms_output.put_line('The description was Very
Good');
when achar = 'C' then dbms_output.put_line('The description was
Good');
when achar = 'D' then dbms_output.put_line('The description was
Fair');
when achar = 'F' then dbms_output.put_line('The description was
Poor');
else dbms_output.put_line('The description was No such Grade');
end case;
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 4:
This sample demonstrates the proper syntax for a case expression of
the
type discussed in Sample 3 above.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
achar char(1) := '&achar';
description varchar2(20);
begin
description :=
case
when achar = 'A' then 'Excellent'
when achar = 'B' then 'Very Good'
when achar = 'C' then 'Good'
when achar = 'D' then 'Fair'
when achar = 'F' then 'Poor'
else 'No such grade'
end;
dbms_output.put_line('The description was ' || description);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 5:
This sample demonstrates the use of nested case statements. It is
also
permissable to nest case expressions within a case statement (though
it
is not demonstrated here), but nesting of case statements within a
case
expression is not possible since statements do not return any value.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
anum1 number := &anum1;
anum2 number := &anum2;
answer number;
begin
case anum1
when 1 then case anum2
when 1 then answer := 10;
when 2 then answer := 20;
when 3 then answer := 30;
else answer := 999;
end case;
when 2 then case anum2
when 1 then answer := 15;
when 2 then answer := 25;
when 3 then answer := 35;
else answer := 777;
end case;
else answer := 555;
end case;
dbms_output.put_line('The answer is ' || answer);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 6:
This sample demonstrates nesting of case expressions within another
case
expression. Note again the absence of semicolons to terminate both
the
nested case expression and the individual cases of those
expressions.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
declare
anum1 number := &anum1;
anum2 number := &anum2;
answer number;
begin
answer :=
case anum1
when 1 then case anum2
when 1 then 10
when 2 then 20
when 3 then 30
else 999
end
when 2 then case anum2
when 1 then 15
when 2 then 25
when 3 then 35
else 777
end
else 555
end;
dbms_output.put_line('The answer is ' || answer);
end;
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Although PL/SQL anonymous blocks have been used in all of the examples
so far,
case statements and expressions can also be used in procedures,
functions, and
packages with no changes to the syntax.
The following samples are included for completeness and demonstrate the
use of
case statements and/or expressions in each of these scenarios.
Sample 7:
This sample demonstrates use of a case statement in a stored
procedure.
Note that this sample also demonstrates that it is possible for each
of
the items in the case body to consist of more than one statement.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace procedure testcasestmt ( anum IN number ) is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
end;
exec testcasestmt(&anum);
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 8:
This sample demonstrates the use of a case statement in a stored
package.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace package testpkg2 is
procedure testcasestmt ( anum IN number );
function testcasestmt_f ( anum IN number ) return number;
end testpkg2;
create or replace package body testpkg2 is
procedure testcasestmt ( anum IN number ) is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
end;
function testcasestmt_f ( anum IN number ) return number is
begin
case
when anum = 1 then dbms_output.put_line('The number was One');
dbms_output.put_line('In case 1');
when anum = 2 then dbms_output.put_line('The number was Two');
dbms_output.put_line('In case 2');
when anum = 3 then dbms_output.put_line('The number was Three');
dbms_output.put_line('In case 3');
when anum = 4 then dbms_output.put_line('The number was Four');
dbms_output.put_line('In case 4');
when anum = 5 then dbms_output.put_line('The number was Five');
dbms_output.put_line('In case 5');
else dbms_output.put_line('The description was Invalid input');
dbms_output.put_line('In the else case');
end case;
return anum;
end;
end testpkg2;
exec testpkg2.testcasestmt(&anum);
variable numout number
exec :numout := testpkg2.testcasestmt_f(&anum);
print numout
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
Sample 9:
This sample demonstrates the use of a case expression in a stored
package.
- - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
set serveroutput on
create or replace package testpkg is
procedure testcase ( anum IN number );
function testcase_f ( anum IN number ) return number;
end testpkg;
create or replace package body testpkg is
procedure testcase ( anum IN number ) is
anumber number := anum;
anothernum number;
begin
anothernum :=
case
when anumber = 1 then anumber + 1
when anumber = 2 then anumber + 2
when anumber = 3 then anumber + 3
when anumber = 4 then anumber + 4
when anumber = 5 then anumber + 5
else 999
end;
dbms_output.put_line('The number was ' || anothernum);
end;
function testcase_f ( anum IN number ) return number is
anumber number := anum;
anothernum number;
begin
anothernum :=
case
when anumber = 1 then anumber + 1
when anumber = 2 then anumber + 2
when anumber = 3 then anumber + 3
when anumber = 4 then anumber + 4
when anumber = 5 then anumber + 5
else 999
end;
dbms_output.put_line('The number was ' || anothernum);
return anothernum;
end;
end testpkg;
variable numout number
exec testpkg.testcase(&anum);
exec :numout := testpkg.testcase_f(&anum);
print numout
- - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
제약 사항
다음의 databasetype은 case 문에서 지원되지 않는다.
BLOB
BFILE
VARRAY
Nested Table
PL/SQL Record
PL/SQL Version 2 tables (index by tables)
Object type (user-defined type)
All of these types except for object types face a similar restriction
even for if statements (i.e. they cannot be compared for equality directly) so this is unlikely to change for these types. Lack of support for object types is simply an implementation restriction which may be relaxed in future releases.
Reference Ducumment
Oracle 8.1.7 Manual
NOTE:131557.1I have done the following code but doesn't
like the statement of - "case(butNext)". What do you mean "doesn't like" -- did you get an error message?
I'm guessing it won't compile because you're trying to switch on a Button.
I tried something
like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"...no that doesn't make sense. You only use BorderLayout.NORTH when you're adding components to a BorderLayout layout manager. An oval is not a component and fillOval isn't adding a component and Graphics is not a Panel or layout manager.
Would appreciate it if someone could tell me how to position
shapes using the graohic method. I think the problem is that you're confusing shapes with components. -
Need help on case statements to validate records
Hi Experts ,
My table :
seq_num
col2
col3
col4
1
A
12345
P
2
B
1
123%23
3
C
1
23AB
4
D
1
20131001
5
E
1
6
A
13245
Q
7
B
1
12345
8
C
2
1234*AB
9
D
5
20140112
10
E
1
00020
my output
seq_num
col2
col3
col4
Status
Reason
1
A
12345
P
Valid
2
B
1
123%23
invalid
Special Character for col4
3
C
1
23AB
Valid
4
D
1
20131001
Valid
5
E
1
invalid
null for col4
6
A
13245
Q
invalid
Invalid character col4 || invalid number for col3
7
B
1
12345
Valid
8
C
2
1234*AB
Invalid
Special Character col4 ||invalid col3
9
D
5
20140112
invalid
Future dates col4 ||invalid col3
10
E
1
00020
Valid
Sql :
with t as
( select 1 as seq_num,'A' as col2 ,12345 as col3 ,'P' as col4 from dual
union all
select 2 ,'B',1,'123%23' from dual
union all
select 3,'C',1,'23AB' from dual
union all
select 4,'D',1,'21-02-2013' from dual
union all
select 5,'E',1,null from dual
union all
select 6,'A,13245,'Q' from dual
union all
select 7,'B',1,12345 from dual
union all
select 8,'C',2,'1234*AB' from dual
union all
select 9,'D',5,'25-01-2014' from dual
union all
select 10,'E',1,20 from dual
I am applying rules on col3 and col4 for each records row-wise.
I need case statements to populate status and reason columns after applying below rules
Rules
Col3 :
For A record ,it should be 12345 always .
For B,C,D,E , record should be always 1
col4
For A record , it should be either P or R
No null values for all A, B,C,D,E records
for B record , it dont contain special charecters
for C RECORD , it dont contain special charecters
for D record ,it should not contain future dates (dates are in yyyymmdd format and less than sysdates are valid )
I have other columns as well ,as i not included here
.It would be great if you Could help on case statements
Thanks and Regards,
SumanthI've adjusted Gregs nice example a bit. This should work:
with w_base as (
select seq_num, col2, col3, col4,
case when (col2 = 'A' AND col3 = 12345 )
OR (col2 in ('B','C','D','E') AND col3 = 1)
then '' else '||invalid col3' end ||
case when (col2 = 'A' AND col4 not IN ( 'P', 'R' ) )
then '||invalid col4' else '' end ||
case when (col2 IN ( 'B', 'C' ) AND col4 != translate(col4, 'a!@#$%^*()','a') )
then '||special character for col4' else '' end ||
case when (col2 = 'D' AND col4 >= to_char(sysdate,'yyyymmdd') )
then '||future dates col4' else '' end
reason
from ( select 1 as seq_num, 'A' as col2, 12345 as col3, 'P' as col4 from dual union all
select 2, 'B', 1, '123%23' from dual union all
select 3, 'C', 1, '23AB' from dual union all
select 4, 'D', 1, '20130212' from dual union all
select 5, 'E', 1, null from dual union all
select 6, 'A', 13245, 'Q' from dual union all
select 7, 'B', 1, '12345' from dual union all
select 8, 'C', 2, '1234*AB' from dual union all
select 9, 'D', 5, '20140125' from dual union all
select 10, 'E', 1, '20' from dual )
Select seq_num, col2, col3, col4,
case when reason is null then 'Valid' else 'Invalid' end status,
substr(reason, 3 ) reason
from w_base
It returns
SEQ_NUM
COL2
COL3
COL4
STATUS
REASON
1
A
12345
P
Valid
2
B
1
123%23
Invalid
special character for col4
3
C
1
23AB
Valid
4
D
1
20130212
Valid
5
E
1
Valid
6
A
13245
Q
Invalid
invalid col3||invalid col4
7
B
1
12345
Valid
8
C
2
1234*AB
Invalid
invalid col3||special character for col4
9
D
5
20140125
Invalid
invalid col3||future dates col4
10
E
1
20
Valid
edited some bugs :) now it should be fine! really -
Hi,
Kinda new to this formatted search. Can anyone help me with this question.
I want to make a formatted search to make a column in sales order 'U_ItemType' so that if it is not null/if it is gift or sample, it will enter the value 'Y' in U_FOC. How do i do this?
Also can anyone point me to any resource to learn up on formatted search.
ThanksYou will need to create a query something like:-
[code]SELECT CASE $[$38.U_ItemType.0] WHEN 'Gift' THEN 'Y' ELSE 'N' END[/code]
This will need to compare the value of the U_ItemType in the current row to any conditions you want (eg. = 'Gift'), and return appropriate Y/N value.
Next you need to define the FS on the U_FOC field. When defining it you probably want to set:-
-Search By Saved Query (select query created above)
-Auto Refresh = "Y"
-When existing column altered
-Column = "U_ItemType"
-Display Saved Values
You can find out more about formatted searches in some of the online training courses available on the service marketplace (http://service.sap.com/smb). The training courses are available in the Education section under the heading "Learning Maps / Development Consultants".
Regards,
John. -
Help needed for Formatted Search
Hai Experts,
would like to ask you some clarification on Formatted Search. In the
query I found $http://$44.2.1 given in the criteria part.
In some articles it was mentioned that, the 44 meant for the table
connected with the form and 2 is field index and so on.
Can you please explain how to find out those numbers and field index.
I need to work out planty of FMS to fetch data into
UDF automatically based on user input.
Regards
AnandHi Anand,
You may check these threads first:
Re: Vendor default GL FMS help
Re: Runtime data calculation
Thanks,
Gordon -
Please help: Case Statement - ORA-01722: invalid number Error
Hi All,
I'm trying to use Case statement to recode Cancelled statuses into two groups
'Reject' if the difference between first date and last date is less than 29 and
'Accept' if the difference between first date and last date is greater than 30
Here is my 'test' data:
STATUS FIRST_DATE LAST_DATE
Transfer 10/08/2011 10/09/2011
Mover 10/08/2011 15/09/2011
Cancel 10/08/2011 16/09/2011
Cancel 10/08/2011 5/09/2011
Here is the syntax
select a.*,
(CASE WHEN a.STATUS ='Cancel' THEN (round(a.LAST_DATE-a.FIRST_DATE))
ELSE 0
END) CAN_DAYS,
(CASE WHEN 'CAN_DAYS' >29 THEN 'Reject'
WHEN 'CAN_DAYS' <30 THEN 'Accept'
END) Reject_Accept
from test a
The first CASE statement works fine and gives me this
STATUS FIRST_DATE LAST_DATE CAN_DAYS
Transfer 10/08/2011 10/09/2011 0
Mover 10/08/2011 15/09/2011 0
Cancel 10/08/2011 16/09/2011 37
Cancel 10/08/2011 5/09/2011 26
but the second CASE produces ORA-01722: invalid number Error. It is something to do with the CAN_DAYS data type, Oracle doesn't see it as Numeric i think.
The result i want to see would be
STATUS FIRST_DATE LAST_DATE CAN_DAYS Reject_Accept
Transfer 10/08/2011 10/09/2011 0
Mover 10/08/2011 15/09/2011 0
Cancel 10/08/2011 16/09/2011 37 Accept
Cancel 10/08/2011 5/09/2011 26 Reject
Could someone please help me to fix the syntax?
Thank you in advance,This seems to give you your desired results...
with test as
( select 'Transfer' as status, to_date('10/08/2011') as first_date, to_date('10/09/2011') as last_date from dual union all
select 'Mover' , to_date('10/08/2011') , to_date('15/09/2011') from dual union all
select 'Cancel' , to_date('10/08/2011') , to_date('16/09/2011') from dual union all
select 'Cancel' , to_date('10/08/2011') , to_date('05/09/2011') from dual
select status
, first_date
, last_date
, CAN_DAYS
, CASE
WHEN CAN_DAYS = 0 THEN NULL
WHEN CAN_DAYS < 30 THEN 'Reject'
WHEN CAN_DAYS >= 30 THEN 'Accept'
END Reject_Accept
from ( select status
, first_date
, last_date
, CASE
WHEN STATUS ='Cancel' THEN round(LAST_DATE-FIRST_DATE)
ELSE 0
END CAN_DAYS
from test
; -
Need help in this sql query to use Case Statement
hi All,
I have the below query -
SELECT DISTINCT OFFC.PROV_ID
,OFFC.WK_DAY
,CASE
WHEN OFFC.WK_DAY ='MONDAY' THEN 1
WHEN OFFC.WK_DAY ='TUESDAY' THEN 2
WHEN OFFC.WK_DAY ='WEDNESDAY' THEN 3
WHEN OFFC.WK_DAY ='THURSDAY' THEN 4
WHEN OFFC.WK_DAY ='FRIDAY' THEN 5
WHEN OFFC.WK_DAY ='SATURDAY' THEN 6
WHEN OFFC.WK_DAY ='SUNDAY' THEN 7
END AS DOW
,OFFC.OFFC_OPENG_TIME
,OFFC.OFFC_CLSNG_TIME
FROM GGDD.PROV_OFFC_HR OFFC
WHERE OFFC.PROV_ID='0000600'
WITH UR;
this query is bringing results in 6 differnt rows with opening and closing time for each day separately. I want to generate the data in one row with each day having opening and closing time, so for 7 days, total 14 columns with opening and closing time. But i am not able to do that using case statement.
can somebody help me in achieving that.
thanks,
iamhereHi,
Welcome to the forum!
That's called a Pivot .
Instead of having 1CASE expression, have 14, one for the opening and one for the closing time each day, and do GROUP BY to combine them onto one row.
SELECT OFFC.PROV_ID
, MIN (CASE WHEN OFFC.WK_DAY ='MONDAY' THEN OFFC.OFFC_OPENG_TIME END) AS mon_opn
, MIN (CASE WHEN OFFC.WK_DAY ='MONDAY' THEN OFFC.OFFC_CLSNG_TIME END) AS mon_cls
, MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY' THEN OFFC.OFFC_OPENG_TIME END) AS tue_opn
, MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY' THEN OFFC.OFFC_CLSNG_TIME END) AS tue_cls
FROM GGDD.PROV_OFFC_HR OFFC
WHERE OFFC.PROV_ID = '0000600'
GROUP BY offc.prov_id
;This assumes there is (at most) only one row in the table for each distinct prov_id and weekday. If not, what do you want to do? Post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
The staement above works in Oracle 8.1 and up, but there's a better way (SELECT ... PIVOT) available in Oracle 11. What version are you using? (It's always a good idea to include this when you post a question.)
Edited by: Frank Kulash on Jan 6, 2011 8:22 PM
Maybe you are looking for
-
Calculating and displaying the Length of the side of a triangle
Hi everyone. I am currently working on Dragging and Stretching a triangle on screen. Ive got it working to a certain extent but the only problem is that whenever I go to the point from which i have to drag my triangle i.e. the Left hand Corner of the
-
JDeveloper IDE: Developer Mode Error
Hi All, I am facing an issue after launcing JDEV through /jdevbin/NT/1223_db2dbg_17007206 (JDeveloper IDE for Release 12.2.3 Dev Build 2). I am getting developer mode error after launcing my application. For the error to perish, we need to disable th
-
Bank Payment Wizard file format
Hello Experts, I have requirement of sending bank payment wizard file to bank for payment in ISO 20022 XML format. - which format is generated by default by SAP B1 and - how to convert the output of payment wizard in ISO 20022 XML format.
-
Missing JServ parameters in OAS ?
Hi there, Why doesn't the JServ in OAS support the ApJServEnvVar parameter ? Its supposed to work with JServ 1.1, but using it in the JServ that comes with OAS9i only produces an error message on startup (syntax error). Could it be that, although it
-
What does iMovie (09) do when I select "Export Movie"?
I can't believe this isn't an FAQ, but I can't seem to find the answer anywhere. I love iMovie but, as many people realize quickly, part of what makes iMovie so simple to use is that it assumes certain things so that the endusers don't have to worry