DO CASE ..... END CASE in PL/SQL
HI all,
Is there any equivalent commanad in pl/sql to get the conditional statement which you can get it from DO CASE ... END CASE statements in any other language..
Thanx
Mayur
You can use DECODE if you simply want to return a value based on what was sent in. Otherwise, I think the key way is to just use IF and ELSIF to get done what you need. I don't think there is a CASE or SWITCH, but I could be wrong.
Similar Messages
-
Case, end case statement
Hi all,
name of my internal table is my_tab.i need to calculate the discounts depending upon the condition types(KSCHL) FROM KONV TABLE.
WHEN KSCHL = ZDO1 calulation procedure is in percentage
KSCHL= ZD02 calculation procedure is in fixed amount.
and so on.....
my_tab has fields
my_tab-total
my_tab-discount
if kschl = ZD01, discount = my_tab-total - my_tab-discount
if kschl = ZD02, discount = my_tab-total * my_tab-discount/100.
i wanted to know how to use this in CASE AND END CASE statement.
regards
akmalHi akmal,
chek out this code.
Case kshcl.
when 'ZD01'.
discount = my_tab-total - my_tab-discount.
when 'ZD02'.
if kschl = ZD02, discount = my_tab-total * my_tab-discount/100.
end case.
if you ar looping through the internal table sthen you can do the same af ter the when statements.
regards,
sateesh. -
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. -
Hi,
I tryed to write a cursor with When Case End; construct insted of using Decode, But It is not taking the When Case End; construct inseide a pl/sql cursor. But it is working with simple sql construct.The reason for the odd message you got is that Oracle 9iDB is introducing a CASE statement of its own, although why Oracle have bothered is beyond me: IF...ELSIF...ELSE is a case construct in all but name.
APC -
SCCM CAS & Primary Site Server - Same SQL Database and Reporting Instance
Hi Fellows,
I need to know whether, for SCCM CAS, a dedicated/seperate SQL instance for SCCM CAS a mendatory requirement or recommendation?
Or we can use the same SQL instance used by Primary Site Server?
J.AThere no technical reason not to have the CAS and Primary database in separate instances of the same remote SQL server. However if you are going to deploy a CAS that would suggest a very large number of clients and a very busy infrastructure. In that case
I would RECOMMEND separate SQL servers.
This is a good guide for SQL sizing (but it is only a guide)
http://blog.coretech.dk/kea/system-center-2012-configuration-manager-sql-recommendations/
Gerry Hampson | Blog:
www.gerryhampsoncm.blogspot.ie | LinkedIn:
Gerry Hampson | Twitter:
@gerryhampson -
How to create a case in case management with QM02 link?
Dear Gurus,
I have to create a case in case management with link to t-code QM02. Any help would be appreciated.
Thanks,
GSMHi..
Easy transaction to Case Management customizing is SCASE_CUSTOMIZING. There you have an overview of the customizing of case management.
Also carryon these steps one by one...
Case Management Basic Settings :
Define Number Range Intervals for Case
Define Case Types
Determine Permitted values for attribute
Create values for "Category" attribute
Create values for "Cause" attributes
Create values for "Priority" attribute
Create values for "Reason" for escalation attribute
Assign escalation reasons to an attribute profile
Create values for "Authorization level" attribute
System Modifications
Create status profile
Create Text profile
Create Text Ids
Create Text Profile
Define Logical system for external objects
Enhanced System modifications
Note About Enhanced System Modifications
Define Processes
Set up registry
Create/Change Case Record Model
Create Profiles
Create attribute profile
Create function profile
Create terminology profile
Create Activities for authorization check
Activate application log
Define processes
Create/Change Case Record Model
When u open the Transaction SCASE_CUSTOMIZING , there will be Registry Steps...
Follow them step by step.
Regards,
Eswari. -
Hi all,
Could anyone tell me if it would be supported to pair a two node enterprise edition front end pool inc mirror sql with a one node enterprise edition front end pool inc single sql?
MUCH THANKS.The answer from TechNet found at http://technet.microsoft.com/en-us/library/jj204697.aspx Is, and I quote:-
Enterprise Edition pools can be paired only with other Enterprise Edition pools. Similarly, Standard Edition pools can be paired only with other Standard Edition pools.
Also, "Neither Topology Builder nor topology validation will prohibit pairing two pools in a way that does not follow
these recommendations. For example, Topology Builder allows you to pair an Enterprise Edition pool with a Standard Edition pool.
However, these types of pairings are not supported."
Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question, please click "Mark As Answer" -
Insurance case,warranty case
Hi
all
what is the significance of insurance case and warranty case in maintenace activity type spro setting
spro-maint order-maintenace activity type-warranty case/insurance case
i do understad if the activty belongs to warranty or insurance you put atick over here
but how we can use it please give me practical example in which this setting could be used.Hi,
commmon guys
It should not be necessary for you to bump up your query in this way especially after less than 1 hour!
You did the same in [this|KDS IN PM; thread but have never bothered updating or closing the thread in the past 12 days. Where you get help give some acknowledgment to those who have assisted you.
If you don't get a response to a query then consider that your issue is not clear. Clarify what information you are looking for, give information on what you have found yourself, etc.
Check the forum [rules|https://www.sdn.sap.com/irj/sdn/wiki?path=/display/home/rulesofEngagement] in particular:
Step 2: Asking Your Question
- Provide Enough Information
- Why is Nobody Answering my Question?
Step 3: Provide Feedback and an Update
Step 4: Thank Others by Giving Points
I'm now going to lock this thread.
-Paul
Moderator, EAM Forum -
Multiple cases based on Columns In SQL Query
There is a SQL query given below, that query performs DateDIff operation by selecting max and min date according to
TCard OR you can say id,
here' the query
SELECT
--COUNT(DIFF)
Count(DATEDIFF(D, MinDate, MaxDate)/30) AS DIFF
FROM (
SELECT
MAX(TDate) AS MaxDate,
MIN(TDate) AS MinDate
FROM EDATA
GROUP BY TCard
)a
Group by DATEDIFF(D, MinDate, MaxDate)/30
Now i want to apply some kind of sorting in this query before performing DateDiff operation (sorting can be based on several parameters
like age, name etc. but 1 at a time according to the cases)
Now I want to know How to apply cases over this query and where?You can apply sorting based on certain condition however you need to include those columns in your subquery. On custom sorting check out this article
here:
e.g.
SELECT CountryName
FROM dbo.Country
ORDER BY CASE WHEN
CountryName = 'INDIA' THEN '1'
WHEN CountryName = 'CHINA' THEN
'2'
ELSE CountryName END ASC
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Is a Full Text Index search case sensitive or not in SQL Server 2012?
I setup full text index on my contact table and am attempting to run a search on it using the following query:
SELECT *
FROM sysdba.Contact C
WHERE CONTAINS(C.FirstName, 'Test')
OR CONTAINS(C.LastName, 'Test')
The problem is it's clearly running a case sensitive search. I did a quick search to find out how to change it to be case in-sensitive and found two pages (both for SQL Server 2012) with conflicting answers:
1 - MSDN - "Query with Full-Text Search" - http://msdn.microsoft.com/en-us/library/ms142583(v=sql.110).aspx
Case sensitivity
Full-text search queries are case-insensitive. However, in Japanese, there are multiple phonetic orthographies in which the concept of orthographic normalization is akin to case insensitivity (for example, kana = insensitivity). This type of orthographic normalization
is not supported.
1 - TechNet - "Full-Text Search (SQL Server)" - http://technet.microsoft.com/en-us/library/ms142571(v=sql.110).aspx
Full-text queries are
not case-sensitive. For example, searching for "Aluminum" or "aluminum" returns the same results.
Can someone please explain this? Is it possible to do it without it being case sensitive? If yes, how?
(Sorry, I couldn't make those links b/c TechNet hasn't verified my account)
Thank you for your time and help,
HananWhats the collation setting for the columns? try using a case insensitive collation as below
SELECT *
FROM sysdba.Contact C
WHERE CONTAINS(C.FirstName COLLATE SQL_Latin1_General_CP1_CI_AS, 'Test')
OR CONTAINS(C.LastName COLLATE SQL_Latin1_General_CP1_CI_AS, 'Test')
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Count (case when) not working in sql
Hi All,
I am trying to find the count of members for a perticular date range, it seems not working correclty.
Could any one help me out.
here is the query...I am getting same output for all the cases..please help
Select
t
.MemberNbr,t.patcom
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between
-1
and
-365
then t.MemberNbr
else 0
end)as
edvisits365daysprior
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 3
then t.MemberNbr
else 0
end)as
edvisits3Days
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 30
then t.MemberNbr
else 0
end)as
edvisits30Days
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 60
then t.MemberNbr
else 0
end)as
edvisits60Days
count(case
when
datediff(d,
mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between 1
and 90
then t.MemberNbr
else 0
end)as
edvisits90Days
--,*--membernbr,specificdateofservice,count( membernbr)--, specificdateofservice)as visitcount--, patcom
--Into #Tmp_PPCSEDCnt1
From
stg_tbl_InPatientPrepost Mbrs
join
#Tmp_MCCSEDVisits t
on
mbrs.MemberNbr=t.MemberNbr
--where UPPER(t.MR_Line_Desc) in ('FOP EMERGENCY ROOM - HOSPITAL', 'FOP EMERGENCY ROOM Urgent Care',
--'PROF ER VISITS AND OBSERVATION CARE')
group
by t.MemberNbr,t.patcomYou may replace 0 as NULL and see how it works for you?
eg:
count(case when datediff(d, mbrs.DischargeDate,
convert(datetime,convert(varchar(12),t.specificdateofservice),112))
between -1 and -365 thent.MemberNbr else NULL end)as edvisits365daysprior -
I need to load distinct enames to target table emp.
1st condition: check the latest mod_time of ename whether active or inactive status
2nd condition: if last mod time is same for one ename check emp_status='ACTIVE' load active record
3rd condition if the ACTIVE records are more than on take max(emp_id)
Emp source table
emp_id ename mod_date emp_status
103 MARY 22-JAN-2012 INACTIVE
104 MARY 21-JAN-2012 ACTIVE
100 john 21-JAN-2012 ACTIVE
101 john 21-JAN-2012 INACTIVE
102 john 21-JAN-2012 ACTIVE
105 JUHI 21-JAN-2012 INACTIVE
106 JUHI 21-JAN-2012 ACTIVE
107 CHEN 21-JAN-2012 INACTIVE
108 CHEN 22-JAN-2012 ACTIVE
109 james 21-JAN-2012 INACTIVE
110 james 22-JAN-2012 INACTIVE
EXPECTED OUTPUT emp target
emp_id ename mod_date emp_status
103 MARY 22-JAN-2012 INACTIVE --take latest mod_time first priority check.
102 john 21-JAN-2012 ACTIVE --first check latest mod_time. since two active records with the same mod_time then take max(emp_id)
106 JUHI 21-JAN-2012 ACTIVE --two records with same mod_time with status active and inactive. take active record.
108 CHEN 22-JAN-2012 ACTIVE --active is the latest mod time
110 james 22-JAN-2012 INACTIVE -- two records with same mod_time with status active take max(emp_id)---------------------------
how can i implement this logic with one sql command and insert into emp_target table
I should have only one record per employee from source
Edited by: choti on Feb 21, 2013 4:58 PMNot sure that this is the most elegant way to do this, but...
WITH emp AS
SELECT 103 emp_id, 'MARY' ename, '22-JAN-2012' mod_date, 'INACTIVE' emp_status FROM dual UNION ALL
SELECT 104, 'MARY', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
SELECT 100, 'john', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
SELECT 101, 'john', '21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
SELECT 102, 'john', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
SELECT 105, 'JUHI', '21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
SELECT 106, 'JUHI', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
SELECT 107, 'CHEN', '21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
SELECT 108, 'CHEN', '22-JAN-2012', 'ACTIVE' FROM dual UNION ALL
SELECT 109, 'james','21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
SELECT 110, 'james','22-JAN-2012', 'INACTIVE' FROM dual
emp1 AS (
SELECT emp_id, ename, mod_date, emp_status, MAX(mod_date) OVER (PARTITION BY ename) max_mod_date
FROM emp
emp2 AS (
SELECT emp_id, ename, mod_date, emp_status, MIN(emp_status) OVER (PARTITION BY ename, mod_date) min_emp_status
FROM emp1
WHERE mod_date = max_mod_date
emp3 AS (
SELECT emp_id, ename, mod_date, emp_status, MAX(emp_id) OVER (PARTITION BY ename, mod_date, emp_status) max_emp_id
FROM emp2
WHERE min_emp_status = emp_status
emp4 AS (
SELECT *
FROM emp3
WHERE max_emp_id = emp_id)
SELECT emp_id, ename, mod_date, emp_status
FROM emp4
EMP_ID ENAME MOD_DATE EMP_STATUS
103 MARY 22-JAN-2012 INACTIVE
102 john 21-JAN-2012 ACTIVE
106 JUHI 21-JAN-2012 ACTIVE
108 CHEN 22-JAN-2012 ACTIVE
110 james 22-JAN-2012 INACTIVE 5 rows selected.
Note: I manually re-ordered the result set so that it matches your expected results.
Edited by: user1983440 on Feb 21, 2013 10:55 PM -
Control on lower case upper case
Hi,
I have one internal table say it_tab....i am converting this table into xml file....fields of internal table is equal to xml tag, for example i have defined internal table field name as "Product" so xml tag will be Product.....but my problem is that sap automatically convert internal table field name in uppercase....i want XML tag as "Product" instead of "PRODUCT" or "product"
Please help me how can i control this. Here is the example:
data: begin of it_tab occurs 0,
Product type string,
end of it_tab.
so after generate XML file XML tag should be: Product.using TRANSLATE convert the whole field name to lowercase 'product'>> using offset ( field+0(1) ) convert the first character to upper case 'Product', and modify your internal table accordingly.
dont think there s any FM or direct method to do this.
Edited by: AJ Nayak on Feb 27, 2012 3:21 PM -
I am trying to set up a join where what fields are matched depend on the value of another field but cannot seem to get the syntax right. I have only posted part of the query as it is quite long and the rest has no relevance to the join.
The error is
Msg 102, Level 15, State 1, Line 59
Incorrect syntax near '='.
on the line
then CertNo =
Can anybody help me sort this out please?
regards
Ron
from
InvoiceItems
join Invoices on inv_no = invit_invno and inv_canind <> 'Y' and inv_cust <> '$sayrf'
join Customers on cust_no = inv_cust
join Stock on stock_no = invit_partno
join Batches on batch_batch = invit_batch and batch_part = invit_partno
inner join Certtable on
case when certpord = ''
then CertNo =
CASE WHEN LEFT(invit_cert,5) = 'HAPAG' then 'HAPAGL'
WHEN LEFT(invit_cert,5) = 'UAMMA' then 'UAMMAERSK'
WHEN LEFT(invit_cert,5) = 'UAMRB' then 'UAMRB211'
WHEN LEFT(invit_cert,5) = 'NSKCON' then 'NSKCON'
ELSE invit_cert
end
else certpord = batch_order
end
join Suppliers on supplierRef = supp_noBecause you are thinking of CASE as a control-of-flow construct - it is not. It is an expression that returns a scalar value. You can use it within a join clause but it must be done correctly. Case returns a scalar value which must be used
to form a Boolean expression. You currently have
case when certpord = ''
then CertNo =
CASE WHEN LEFT(invit_cert,5) = 'HAPAG' then 'HAPAGL'
WHEN LEFT(invit_cert,5) = 'UAMMA' then 'UAMMAERSK'
WHEN LEFT(invit_cert,5) = 'UAMRB' then 'UAMRB211'
WHEN LEFT(invit_cert,5) = 'NSKCON' then 'NSKCON'
ELSE invit_cert
end
else certpord = batch_order
end
Reducing this to remove the specific logic within the nested expression, you have
case when certpord = ''
then CertNo = [c1]
else certpord = batch_order
end
So it should be obvious that you are attempting to treat the case expression as a control-of-flow statement. Usually it is easier to write the logic twice and then combine the queries into a single one (if that is possible). I'm guessing that
you need something like:
inner join Certtable on
(certprod = '' and (case left(invit_cert,5) when 'HAPAG' then 'HAPAGL' ... else invit_cert end) = CertNo)
or (certpord <> '' and certpord = batch_order)
Carefully consider the logic if certprod can be null. And a last comment. You should get into the many best practices habits - one of which is to give an alias to each table and to use always the alias when referencing columns in each table.
This makes it easier to find logic problems based on the presence of similar column names in different tables and it improves the ability of your reader to understand the query and the association of columns to tables and tables to tables. If you
find that the logic used to translate left(invit_cert, 5) appears frequently, you should consider adding a computed column to the associated table (and perhaps materializing it and /or the relationship).
And another note - don't write/implement code that serves no useful purpose. The last condition of your embedded case expression does nothing useful.
WHEN LEFT(invit_cert,5) = 'NSKCON' then 'NSKCON'
The above condition can be safely left out of the logic since it will be evaluated in the same fashion as the else condition of the case expression. -
How to "end" function definition in SQL plus?
I am using Oracle 11g and SQL plus.
I am trying to define a function and get back to the SQL prompt, but it is just not exiting the function definition.
SQL> create function dept_count (dept_name varchar(20))
2 returns integer
3 begin
4 declare d_count integer;
5 select count (* ) into d_count
6 from instructor
7 where instructor.dept_name = dept_name
8 return d_count;
9 end
10 ;
11
12
13
14
15
16 ;;;
17 end dept_count;
18 ;
19
20 ; <--- I was expecting the SQL> prompt here but it doesn't appear.
What should I do? Please help. Thanks.And, to answer probably the most frequently asked question when I was an Oracle instructor ...
If you are saving this statement in a file to execute later, after the "/" at the bottom, hit return, so that your file contains a line feed after the /, rather than your file ending with the /
Otherwise you get the annoying, but completely harmless, error message "Input truncated after (number) characters" when you compile the program.
Maybe you are looking for
-
Urgent - Messages in RWB in "System Error" status - Resending
All, I am trying to resend the messages in Message Monitoring of RWB which are in "System Error". Message selected and Clicked on resend and it would not ask my password. We are on SP19 of XI 3.0. Is it something new with the SP19? I am pretty much s
-
How to display labels ( vertically) in a column Chart
Hi, As per my requirement I want to show labels inside the column charts & they must be aligned verically say ABC is id i want display i want A B
-
NEF files aren't working in the newly updated Camera Raw nor in CS6.
I'm using the Nikon D600. It says it supports it. Did all the updates and still not working! Any clues as to what the problem might be?
-
Warranty - how does it work?
after 5 happy years with Creative Zen, I've switched religion, and got an ipod Classic 120GB. sadly, 3 weeks after loading it up, the screen failed (no display, just went white and didn't work properly). reset and a restore didn't make any difference
-
Central is pausing my "other instances" of Central - can I stop this??
We have 9 instances of Central Output Server 5.6 installed on a server running Windows 2003. We are currently using one instance, call it instance 1. When the server is rebooted for whatever reason, all the Central Output Server restarts all the in