Case statement on Variable SSIS
Hi friends,
I have a small issue in my package I would like to write a case statement on Variable or Column in derived column Transformation
I was using forloop container that pulls the data from different database so the database names also loading into table under one of the column but I wanna load with integer value instead database name
for example
Database A -- 1
Database B -- 2
so I would like to write a case statement on variable or column but It was not allowing me to write when I tried.
what I have tried was I took one derived transformation and added one new column and passed that variable to that new column.
then again I took another derived transformation here I was trying to write case statement on the colum which is belongs to previous derived column.
Derived Column Tran 1:
Derived Column Name Expression DataType
RegionID @[User::InitialDB] Unicodestring[DT_WSTR]
Derived Column Tran2:
Can anyone please check and guide me the solution please.
Thanks for your help
Hi BandSr,
You were close, just missing the false part in your second conditional operator.
[RegionID] == "KAPS" ? "1" : [RegionID] == "LAPS"? "2" : ""
In fact, I won't call that a Case statement but rather a nested conditional expression.
Hope this helps.
~ J.
Similar Messages
-
More than one variable at a time in case statement
hi i am using oracle 10g database.
can it be possible ?
in if condition we can have more than one variable in one condition
if a=100 then
b:=200;
c:=300;
end if;
how it will be in case statement ? i have searched lot on internet but didnt get
case
when a=100 then 200, 300 ... ???
thanksHi FRNzzz!! wrote:
hi i am using oracle 10g database.
can it be possible ?
in if condition we can have more than one variable in one condition
if a=100 then
b:=200;
c:=300;
end if; how it will be in case statement ? i have searched lot on internet but didnt get
case
when a=100 then 200, 300 ... ???
thanksnot sure if I got your question correctly, is this what you are looking for?
SQL> ed
Wrote file afiedt.buf
1 declare
2 a number := 100;
3 b number;
4 c number;
5 begin
6 case
7 when a = 100 then
8 b := 200;
9 c := 300;
10 when a = 0 then
11 b := 300;
12 c := 400;
13 else
14 b := 0;
15 c := 0;
16 end case;
17 dbms_output.put_line('a :'||a||' b :'||b||' c :'||c);
18* end;
SQL> /
a :100 b :200 c :300
PL/SQL procedure successfully completed. -
SQL Expression Field - Combine Declared Variable With Case Statement
Hello All, I have been using Crystal & Business Objects for a few months now and have figured out quite a bit on my own. This is the first real time I have struggled with something and while I could do this as a Formula Field I would like to know how to do this as a SQL Expression. Basically I want to create a SQL Expression that uses a CASE statement but I wanted to make the code a little more efficient and employ a variable to hold a string and then use the variable in the CASE statement. The expression editor accepts the CASE statement OK but I don't know how to declare the variable. Please assist with the syntax?
This is what I have:
CASE
WHEN u201CDatabaseu201D.u201DFieldu201D = u2018Hu2019 THEN u2018Hedgeu2019
WHEN u201CDatabaseu201D.u201DFieldu201D = u2018Pu2019 THEN u2018PVIu2019
ELSE u2018Noneu2019
END
This is what I want:
DECLARE strVar AS VARCHAR(25)
strVar = u201CDatabaseu201D.u201DFieldu201D
CASE
WHEN strVar = u2018Hu2019 THEN u2018Hedgeu2019
WHEN strVar = u2018Pu2019 THEN u2018PVIu2019
ELSE u2018Noneu2019
ENDHi Todd,
Please use the following for loop; your problem will be solved.
Local StringVar str := "";
Local NumberVar strLen := Length ({Database.Field});
Local NumberVar i;
For i := 1 To strLen Do
if {Database.Field} <i> = "H" then str := "Hedge"
else if {Database.Field} <i> = "P" then str := "PVI"
else str := "None"; exit for
str
Let me know once done!
Thank you,
Ashok -
Issue with referencing Presentation variables(Date cols) in Case statement
Hi,
I m trying to reference presentation variables created on a Date column in the case statement of one of the request's columns as shown below:
case when "- Quote Details"."Creation Date" between '@{from}{1999-1-1}' and '@{until}{2999-1-1}' then "- Quote Metrics"."# of Quotes" end
I m getting a view display error with the below error message:
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1861, message: ORA-01861: literal does not match format string at OCI call OCIStmtExecute
SQL Issued: SELECT "- Quote Types"."Level2 Name" saw_0, case when "- Quote Details"."Creation Date" between '4/1/2009' and '4/15/2009' then "- Quote Metrics"."# of Quotes" end saw_1 FROM "(Unity) Quotes Catalog" WHERE "- Quote Details"."Creation Date" BETWEEN timestamp '2009-04-01 00:00:00' AND timestamp '2009-04-15 00:00:00' ORDER BY saw_0
When I created the prompt on the date field I put the following formula in the prompt:
cast("- Time".Day as DATE)
When I apply a filter on the request using these variables it works fine.
If anyone has faced this kind of issue earlier and have a resolution, please help me out.
Thanks,
KartikThanks Goran!!
I've created prompts by selecting columns from the logical tables (i.e. I've selected 2 different cols of datatype DATE...inorder to assign 2 presentation variables).
Yes I m using calendar widget for prompts.
I haven't included any filter in my report. I m trying to display a metric when it satisfies the case statement.
I will defintley go through the blogs you mentioned for better understanding.
Thanks,
Kartik
Query fired on physical db:
WITH
SAWITH0 AS (select D1.c1 as c1,
D1.c2 as c2,
D1.c3 as c3,
D1.c4 as c4,
D1.c5 as c5
from
(select T192898.QLS_FIRST_ACAP_DT as c1,
TO_DATE('3/2/2009','mm/dd/yyyy') as c2,
TO_DATE('4/29/2009','mm/dd/yyyy') as c3,
T188666.LEVEL2_NAME as c4,
T188666.ID as c5,
ROW_NUMBER() OVER (PARTITION BY T188666.ID, T192898.QLS_FIRST_ACAP_DT ORDER BY T188666.ID ASC, T192898.QLS_FIRST_ACAP_DT ASC) as c6
from
XXSLS_GBL_QTE_TYPES_V T188666,
XXSLS_GBL_QTE_DTL_F T192898
where ( T188666.ID = T192898.QUOTE_TYPE_ID )
) D1
where ( D1.c6 = 1 ) ),
SAWITH1 AS (select D1.c1 as c1,
D1.c2 as c2,
D1.c3 as c3
from
(select count(distinct T192898.QUOTE_HEADER_ID) as c1,
T188666.LEVEL2_NAME as c2,
T188666.ID as c3,
ROW_NUMBER() OVER (PARTITION BY T188666.ID ORDER BY T188666.ID ASC) as c4
from
XXSLS_GBL_QTE_TYPES_V T188666,
XXSLS_GBL_QTE_DTL_F T192898
where ( T188666.ID = T192898.QUOTE_TYPE_ID )
group by T188666.ID, T188666.LEVEL2_NAME
) D1
where ( D1.c4 = 1 ) ),
SAWITH2 AS (select D1.c1 as c1,
D1.c2 as c2,
D1.c3 as c3
from
(select case when SAWITH1.c2 is not null then SAWITH1.c2 when SAWITH0.c4 is not null then SAWITH0.c4 end as c1,
case when SAWITH0.c1 between SAWITH0.c2 and SAWITH0.c3 then SAWITH1.c1 else NULL end as c2,
case when SAWITH0.c5 is not null then SAWITH0.c5 when SAWITH1.c3 is not null then SAWITH1.c3 end as c3,
ROW_NUMBER() OVER (PARTITION BY case when SAWITH0.c5 is not null then SAWITH0.c5 when SAWITH1.c3 is not null then SAWITH1.c3 end , case when SAWITH1.c2 is not null then SAWITH1.c2 when SAWITH0.c4 is not null then SAWITH0.c4 end ORDER BY case when SAWITH0.c5 is not null then SAWITH0.c5 when SAWITH1.c3 is not null then SAWITH1.c3 end ASC, case when SAWITH1.c2 is not null then SAWITH1.c2 when SAWITH0.c4 is not null then SAWITH0.c4 end ASC) as c4
from
SAWITH0 full outer join SAWITH1 On SAWITH0.c5 = SAWITH1.c3
) D1
where ( D1.c4 = 1 ) )
select SAWITH2.c1 as c1,
SAWITH2.c2 as c2
from
SAWITH2
order by c1 -
SSIS: Using CASE Statement Within A Derived Column Transformation Expression
The following is my Data Flow:
Ole DB Source > Copy Column > Derived Column >Ole DB Command
My OLE DB Source has the following SQL command task:
SELECT *
FROM Repair R
LEFT OUTER JOIN Vehicle V
ON R.SN = V.SN
AND R.Reg = V.Reg
LEFT OUTER JOIN Product P
ON R.PID = P.PID
This yields a column of concern for me named PartNumber, which are represented by the following 2 formats:
The following are my Copied Columns:
Input Column = PartNumber
Output Alias = Copy of PartNumber
The following are my Derived Column expressions:
Derived Column Name Derived Column Expression
Name Replace 'PartNumber' LEFT(PartNumber,FINDSTRING(PartNumber,"-",1) - 1)
Copy of Name Replace 'Copy of PartNumber' RIGHT([Copy of PartNumber],LEN([Copy of PartNumber]) - FINDSTRING([Copy of PartNumber],"-",1))
So My PartNumber Column is Replaced with ######### of type
string and the Copy of PartNumber column is replaced with
#### of type int
As I stated earlier PartNumber also is in the format of %-%-% which raises the following question:
How can I replace PartNumber Column with NULL if in format of
%-%-% and take the PartNumber and put it in new column named
SubPart while keeping all the logic within SSIS objects?
So in essence I want to do something like the following:
PartNumber = CASE
WHEN 'PartNumber' LIKE '%-%-%'
THEN ABC = PartNumber AND PartNumber IS NULL
END
I have tried the case statement in a Derived Column expression and is not working. Would I add the
CASE statement to the SQL command task in my OLE DB Source?
I hope this question is concise for you.If it must be in SSIS, I would put a derived column stage earlier in the process to do my check for me. Then in the second derived column stage do the check against each output column (part, subpart, copy of part) to decide which way it goes
PS Not sure if it's a 2012 function but SSIS has a function called TOKEN that will allow you to pull your subparts for you rather than the left/right you are doing -
Naming the evaluated case statement field with concatenating input variable value
Hi,
I am trying to add the input variable value to case statement evaluated field like below query:
declare @Year varchar(4)
select ProductCode,datepart(mm,Date) MonthValue,
case when datepart(mm,Date) = 1 then sum(Price) else 0 END AS Jan+@Year,
case when datepart(mm,Date) = 2 then sum(Price) else 0 END AS Feb+@Year,
case when datepart(mm,Date) = 3 then sum(Price) else 0 END AS Mar+@Year,
case when datepart(mm,Date) = 4 then sum(Price) else 0 END AS Apr+@Year,
case when datepart(mm,Date) = 5 then sum(Price) else 0 END AS May+@Year,
case when datepart(mm,Date) = 6 then sum(Price) else 0 END AS Jun+@Year,
case when datepart(mm,Date) = 7 then sum(Price) else 0 END AS Jul+@Year,
case when datepart(mm,Date) = 8 then sum(Price) else 0 END AS Aug+@Year,
case when datepart(mm,Date) = 9 then sum(Price) else 0 END AS Sep+@Year,
case when datepart(mm,Date) = 10 then sum(Price) else 0 END AS Oct+@Year,
case when datepart(mm,Date) = 11 then sum(Price) else 0 END AS Nov+@Year,
case when datepart(mm,Date) = 12 then sum(Price) else 0 END AS Dec+@Year
from Sales_Imports where datepart(yyyy,Date) = @Year
group by ProductCode, datepart(mm,Date)
Please help me any other way as this is not working...
Thanks,
Srinicreate table Sales_Imports (ProductCode int, Price int, [date] date)
insert into Sales_Imports values
(1,10,'1/1/2014'),(1,109,'2/1/2014'),(1,10,'1/1/2014'),(1,109,'12/1/2014'),
(2,10,'1/1/2014'),(2,109,'2/1/2014'),(2,10,'10/1/2014'),(2,109,'12/1/2014')
declare @Year varchar(4)='2014'
DECLARE @MaxCount INT, @SQL NVARCHAR(max) ,@i INT;
Set @MaxCount = 12
SET @i = 0;
SET @SQL = '';
WHILE @i < @MaxCount
BEGIN
SET @i = @i + 1;
SELECT @SQL = @Sql + ', SUM(CASE WHEN datepart(mm,[Date]) = ' + cast(@i AS NVARCHAR(10)) + ' THEN Price Else 0 END) AS ' +Left(DateName(month,Dateadd(month,@i-1,0)) ,3)+@Year
END
SET @SQL = N' SELECT ProductCode, datepart(mm,Date) MonthValue ' + @SQL
+ N' FROM Sales_Imports
where datepart(yyyy,Date) ='+ @Year + N'group by ProductCode, datepart(mm,Date)
Order by ProductCode, datepart(mm,Date)';
--PRINT @SQL;
execute (@SQL);
--Or your original one
declare @Year varchar(4)
Set @Year ='2014'
declare @SQL Nvarchar(4000)
SET @SQL=
N' select ProductCode,datepart(mm,Date) MonthValue,
case when datepart(mm,Date) = 1 then sum(Price) else 0 END AS [jan' +@year+'],
case when datepart(mm,Date) = 2 then sum(Price) else 0 END AS [feb' +@year+'],
case when datepart(mm,Date) = 3 then sum(Price) else 0 END AS [Mar'+@year+'],
case when datepart(mm,Date) = 4 then sum(Price) else 0 END AS [Apr'+@year+'],
case when datepart(mm,Date) = 5 then sum(Price) else 0 END AS [May'+@year+'],
case when datepart(mm,Date) = 6 then sum(Price) else 0 END AS [june'+@year+'],
case when datepart(mm,Date) = 7 then sum(Price) else 0 END AS [july'+@year+'],
case when datepart(mm,Date) = 8 then sum(Price) else 0 END AS [Aug'+@year+'],
case when datepart(mm,Date) = 9 then sum(Price) else 0 END AS [Sep'+@year+'],
case when datepart(mm,Date) = 10 then sum(Price) else 0 END AS [Oct'+@year+'],
case when datepart(mm,Date) = 11 then sum(Price) else 0 END AS [Nov'+@year+'],
case when datepart(mm,Date) = 12 then sum(Price) else 0 END AS [Dec'+@year+']
from Sales_Imports where datepart(yyyy,Date) = ' + @Year +N' group by ProductCode, datepart(mm,Date)'
--print @Query
Execute (@SQL)
drop table Sales_Imports -
Using Presentation variables..along with case statements..
Hi All.
I have a issue using presentation variable along with CASE statements. My approach is
1) I have a dashboard prompt, which is being set as Presentation variable.
Based on the value selected in prompt, for ex the values of prompt can be 'ABC' and 'DEF'.
I have a calculated column, the calculation goes this way...
The forumal is
CASE WHEN @{Presentation Variable Name} = 'ABC' THEN xxxxxxxxxx ELSE IF @{Presentation Variable Name} = 'DEF' END. It gives error of "no table being referenced"..
Is this is the right approach??
Can i get the values of variable in a column formula, so that a column can have values selected in prompt?
Can anybody pls help me here..
Thanks in advance...Hi
Thanks for the quick response..
I agree to ur point..
But the requirement is
Based on the value of the prompt I need to switch the calculation in one of the formula area of one column..
If Prompt value is ABC then one kind of calculation in Fx and If the prompt value is DEF then one kind of calculation in the same Fx..
How can I acheive this?
Thanks in advance.. -
Bind Variable In Case Statement Produces Error ORA-01036
When running the following command using ODP.Net 10.1.0.301 I recieve error 1036. Statement runs fine within SQL+ and Toad.
Dim SQL As String = "SELECT CASE WHEN EXISTS(SELECT part_nbr FROM item_master WHERE part_nbr=:part_number) THEN 1 ELSE 0 END AS RECORD_EXISTS FROM Dual"
Dim OraConnection As New OracleConnection(connectstring)
Dim OraCommand As New OracleCommand(SQL, OraConnection)
OraCommand.Parameters.Add("part_number", OracleDbType.Varchar2).Value = PartNumber
Dim Obj as Object=OraCommand.ExecuteScalarHi Michael,
I was able to get your code to work on my system by changing the SQL statement as follows:
SELECT (CASE WHEN EXISTS(SELECT part_nbr FROM item_master WHERE part_nbr=:part_number) THEN 1 ELSE 0 END) AS RECORD_EXISTS FROM Dual
I simply enclosed the case statement in opening and closing parenthesis...
Hope that helps,
- Mark -
Help With A Case Statement With Multiple Variables
I apologize if this is the incorrect Forum for this type of question, but it was the closest one that I could find. I'm pretty new with SQL and am stuck on this issue. I have roughly 26 dates that I need to compare to one another. Each date is tied to a step code. I also have a Stop value that is tied directly to the "max date" of the step codes. So, I need to compare 30 dates against one another to 1st - ID the max date; 2nd - ID if the Stop value is correct; 3rd - if the stop value is incorrect, identify what the correct value would be.
At first, this seemed like it wouldn't be that hard. I wrote a query that found the max date for each step code. Then I realized that multiple step codes could have the same date. So, I tried using this case statement, but I did not get the expected results. Is there a more efficient way of getting what I need? This code seems like it's not necessary and probably the source of my issue.
CASE
WHEN FS25.ACTUAL_COMPLETION_DATE > FS.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS1.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS2.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS3.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS4.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS5.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS6.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS7.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS8.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS9.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS10.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS11.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS12.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS13.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS14.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS15.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS16.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS17.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS18.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS19.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS20.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS21.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS22.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS23.ACTUAL_COMPLETION_DATE AND FS25.ACTUAL_COMPLETION_DATE > FS24.ACTUAL_COMPLETION_DATE AND L.FORECLOSURE_STOP_CODE <= '8' THEN '9'
ELSE 'UH OH'
END AS "CHANGE FC STOP TO"
Any assistance is appreciated!I think Igor pointed out a working solution before.
Applying it at your examples (you missed the operator after STOP_CODE, I assume it =):
CASE
WHEN FS25 = GREATEST(FS25, FS24, FS23) AND STOP_CODE = '9' THEN '9'
ELSE 'UH OH'
END AS 'CHANGE STOP CODE TO'
{code}
Be careful at the second example. You are checking:
{code:sql}
FS25 > FS24 OR FS25 IS NOT NULL AND FS24 IS NULL AND FS25 > FS23
OR
FS25 IS NOT NULL AND FS23 IS NULL AND STOP_CODE = '9'
{code}
Remember that AND has higher priority among operators than OR so if FS25 is greater than FS24 and FS23 the condition will be true even if STOP_CODE is not equal 9.
Regards.
Al -
Hi,
I have query with a case statement as follows:
SELECT * FROM table
WHERE
CASE WHEN :variable like 'A' THEN column END is null
WHEN :variable like 'B' THEN column END is not null;
This works fine when returning "column is null" but not when "column is not null".
Can I use a CASE statement like this?
Thanks
LucyMy data is too complicated to show, but depending on the value of the bind variable in the statement I want to return all the rows in a query where the data in a particular column is either null or not null.For example, looking at the EMP table, if my bind variable is whether I want to show the top manager or not, if set to 'Yes' I would like to return all rows of the EMP table where mgr is null (i.e. the one row where ename is 'KING'), if it were set to 'No' I would like to return all the rows where mgr is not null (i.e. all the other rows). The difference with my query is that the column contains strings, not numerics.
I've used a CASE statement before where I equate the column to a particular value and that works fine, but I'm not sure how they deal with nulls. I've also tried DECODE and didn't get anywhere with that.
Thanks
Lucy -
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. -
Using a comparison to NULL in a CASE statement
Hi, please could anybody advise me if it is OK to use comparison to NULL in a CASE statement. Alternatively, will a NULL be accepted in a to_number function giving a result of a NULL in the number variable?
I have a list of varchar2 values which will either be a number, be equal to '95%' or be NULL. I need to translate that to a number column, removing the % from 95%.
I would like to know if the syntax below is allowed:
CASE vPurity
WHEN NULL THEN
nPurity = '';
WHEN '95%' THEN
nPurity := 95;
ELSE
nPurity := TO_NUMBER(vPurity);
END CASE;
Many thanks.robust
adj.
1. Full of health and strength; vigorous.
2. Powerfully built; sturdy. See Synonyms at healthy.
3. Requiring or suited to physical strength or endurance: robust labor.
4. Rough or crude; boisterous: a robust tale.
5. Marked by richness and fullness; full-bodied: a robust wine.
By saying "Robust" you are saying that DECODE is somehow stronger or better than CASE. This is not the case (scuse the pun) as CASE is more flexible than DECODE and can be easier to read in the code. CASE also handles non-equality comparisons far easier than can be done in DECODE. -
CASE statement in a dynamic page
I have written a query using a CASE statement in the select portion to evaluate column values and produce a text string. The query runs fine in sql*plus, but when I attempt to add the code to a dynamic page and compile it, I get the following error message:
ORA-06550: line 1, column 720:
PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
( - + mod null <an identifier>
<a double-quoted delimited-identifier> <a bind variable>
table avg count current max min prior sql stddev sum variance
execute the forall time timestamp interval date
<a string literal with character set specification>
<a number> <a single-quoted SQL string> (WWV-11230)
Critical Error in wwerr_api_error.get_errors! SQL Error Message: ORA-06502:
PL/SQL: numeric or value error: character string buffer too small (WWV-)
I am running oracle 8.1.7.1.0 using Portal 3.0.9.8.1
I have written a function as a workaround, but would like to know why portal does not seem to like the "CASE" statement.
Any suggestions would be greatly appreciated.Hi Chetan,
I still get an error message even when I attempt to create a small dynamic page with your cursor. The error message is posted below. I am definitely putting the cursor declaration between <ORACLE></ORACLE> tags. Any Ideas?
Thanks,
Dan
ORA-06550: line 1, column 215:
PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
( - + mod null <an identifier>
<a double-quoted delimited-identifier> <a bind variable>
table avg count current max min prior sql stddev sum variance
execute the forall time timestamp interval date
<a string literal with character set specification>
<a number> <a single-quoted SQL string> (WWV-11230)
Failed to parse as PORTAL30 - DECLARE CURSOR SPN_INMATE_INFO(V_SPN IN VARCHAR2) IS SELECT DISTINCT B.ENAME, B.ENAME||' '||B.ENAME F_NAME, B.DEPTNO, B.SAL, B.HIREDATE, B.SAL, B.EMPNO, B.HIREDATE, B.COMM, B.ENAME, CASE WHEN B.HIREDATE IS NULL THEN 'NO' WHEN B.HIREDATE IS NOT NULL AND B.SAL IS NOT NULL THEN 'NO' WHEN B.SAL IS NOT NULL AND B.HIREDATE IS NULL THEN 'YES' END RELEASED, C.DNAME, C.LOC, C.DEPTNO FROM SCOTT.EMP B, SCOTT.DEPT C WHERE C.DNAME NOT IN ('5397','6497','6498','6499','5011','42-9-44') AND C.LOC NOT IN ('M','F') AND B.ENAME != '00188547' AND B.DEPTNO = C.DEPTNO ORDER BY B.HIREDATE; BEGIN NULL; END; (WWV-08300) -
Decode and case statement in the update..
Its is more to it, but I want to check with you guys, the experts on this, this look busy to me, it should be a more simplify way of doing it, do you think will work
The government decide to change the ethnic codes, and we have to come with certain rules to in our report, anyway, do you think this will work? again It is more to it I declare my variables, this is just one part of the precedure.
BEGIN
UTL_FILE.fclose_all;
v_file_handle := UTL_FILE.fopen (v_out_path, v_out_file, 'a');
UTL_FILE.put_line (v_file_handle,
CHR (10) || TO_CHAR (SYSDATE, 'DD-MON-YYYY HH:MI:SS')
UTL_FILE.put_line (v_file_handle, 'Entering spbpers_update');
SELECT upd_spbpers_upd_cur IS
spriden_pidm,
szscapp_birth_state,
szscapp_birth_city,
DECODE(szscapp_hisp_or_latino_ind,Y,'2',N,'1'),
DECODE(szscapp_hisp_or_latino_options,XCM,'2',CUB,'2',MEX,'2',PRI,'2',XSM,'2',ESP,'2',XOH,'2'),
DECODE(szscapp_amer_indn_alaska_opt,XAN,'1','1',XCW,'1',XCH,'1',XCK,'1',XNV,'1',XSX,'1'),
DECODE(szscapp_amer_indn_alaska_other,XON,'1') (,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),
DECODE(szscapp_asian_options,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'), ,
DECODE(szscapp_other_east_asia,(IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),
DECODE(szscapp_other_indian_subcont,XIS,'1'),
DECODE(szscapp_other_southeast_asia,XSA,'1'),
DECODE(szscapp_blk_or_afr_amer_opt,XAA,'1',XAF,'1',XCB,'1',XOA,'1'),
DECODE(szscapp_blk_or_afr_amer_other,XOA,'1'),
DECODE(szscapp_natve_hawaian_options,GUM,'1',XHI,'1',ASM,'1',XOP,'1'),
DECODE(szscapp_hawaiian_other,XOP,'1'),
DECODE(szscapp_white_options,XEU,'1',XME,'1',XOW,'1'),
DECODE(szscapp_white_other(XOW,'1')
FROM
saturn_midd.szscapp
WHERE
spriden_id = szscapp_id
AND spriden_ntyp_code = 'CAPL'
IF upd_spbpers_upd_cur%ISOPEN
THEN
CLOSE upd_spbpers_upd_cur;
END IF;
OPEN upd_spbpers_upd_cur;
LOOP
FETCH upd_spbpers_upd_cur
INTO v_pidm,v_birth_state,v_birth_city,v_latino_ind,v_latino_options,
v_indn_alaska_opt,v_indn_alaska_other,v_asian_options,
v_other_east_asia,v_other_indian_subcont,v_other_southeast_asia,
v_blk_or_afr_amer_opt,v_blk_or_afr_amer_other,v_natve_hawaian_options,
v_hawaiian_other,v_white_options,v_white_other;
EXIT WHEN upd_spbpers_upd_cur%NOTFOUND;
IF upd_spbpers_upd_cur%FOUND
UPDATE saturn.spbpers
set SPBPERS_ETHN_CODE = CASE
WHEN v_latino_ind IS NOT NULL THEN (spbpers_ethn_code = v_latino_ind,spbpers_activity_date = sysdate)
WHEN v_latino_options IS NOT NULL THEN (spbpers_ethn_code = v_latino_options,spbpers_activity_date = sysdate)
WHEN v_indn_alaska_opt IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_opt,spbpers_activity_date = sysdate)
WHEN v_indn_alaska_other IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_other,spbpers_activity_date = sysdate)
WHEN v_asian_options IS NOT NULL THEN (spbpers_ethn_code = v_asian_options,spbpers_activity_date = sysdate)
WHEN v_other_east_asia IS NOT NULL THEN (spbpers_ethn_code = v_other_east_asia,spbpers_activity_date = sysdate)
WHEN v_other_indian_subcont IS NOT NULL THEN (spbpers_ethn_code = v_other_indian_subcont,spbpers_activity_date = sysdate)
WHEN v_other_southeast_asia IS NOT NULL THEN (spbpers_ethn_code = v_other_southeast_asia,spbpers_activity_date = sysdate)
WHEN v_blk_or_afr_amer_opt IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_opt,spbpers_activity_date = sysdate)
WHEN v_blk_or_afr_amer_other IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_other,spbpers_activity_date = sysdate)
WHEN v_natve_hawaian_options IS NOT NULL THEN (spbpers_ethn_code = v_natve_hawaian_options,spbpers_activity_date = sysdate)
WHEN v_hawaiian_other IS NOT NULL THEN (spbpers_ethn_code = v_hawaiian_other,spbpers_activity_date = sysdate)
WHEN v_white_options IS NOT NULL THEN (spbpers_ethn_code = v_white_options,spbpers_activity_date = sysdate)
WHEN v_white_other IS NOT NULL THEN (spbpers_ethn_code = v_white_other,spbpers_activity_date = sysdate)
WHEN v_birth_state IS NOT NULL THEN (spbpers_stat_code_birth = v_birth_state,spbpers_activity_date = sysdate)
WHEN v_birth_city IS NOT NULL THEN (spbpers_city_birth = v_birth_city,spbpers_activity_date = sysdate)
WHERE spbpers_pidm = v_pidm;
END
END IF;
END LOOP;Did the procedure compile ?
Doesn't look like a right Decode syntax.
DECODE (col1,'VAL1','This','VAL2','That','ElseThis')
means
--Psuedocode
IF col1 = 'VAL1' THEN 'This'
IF col1 = 'VAL2' THEN 'That'
ELSE 'ElseThis'You can use CASE statement Instead of DECODE
CASE
when szscapp_amer_indn_alaska_other
in ('XON','IND','JPN','KOR','PAK' ..... ) THEN '1'
when szscapp_hisp_or_latino_options
in ('XCM','CUB','MEX','PRI','XSM','ESP','XOH' ...) THEN '2'
END SS -
Pushing case statement applied in answers formula to Database
Hi All,
There are three prompts, for which there is a kind of header report with narrative view, now when user selects value in prompt element1 and do not select anything in prompt element 2 and 3, in the header only element1 should be displayed and emlement2,3 and few other elements should be nullified, to do this, i used presentation variables for element2,3 directly in narrative view. but for other non-prompt elements not to show up, i used case statement like:
case when length(@{presntation_var}) > 0 then "display.column" else NULL end
Now OBIEE is executing in such a way that, it is retrieving all the columns from the database and then applying logical case statement at BI server level, I need to push this case statement to DB level, can anyone help me how this could be accomplished.
Thanks,
Sreekanth JalaHi
why cant u use the condition in RPD.
In rpd use the case condition and make that as a one logical column. Test=" Fact"."Service Revenue" / "Fact"."Hours Budget". make it as a logical sum.
Then bring this column in to answerside, and use the case condition
case when
"Fact"."Location" <> 'X'
then
(" Fact""Test")
else
"Fact"."Hourly Rate"
end
Regards,
VG
Maybe you are looking for
-
How can I Access TC outside of my home network?
Hi everyone: I am new to the MAC World. We just bought my daughter a Mac Book Pro to use in University then added the time capsule at home so she would be able to back up her work over the internet and we would be able to use the WIFI and TC here at
-
When I try to sync my iPhone it start first with backing up and it takes forever, then it starts with transfering purchases etc. How can I avoid that? I would like only to ad one or two albums or one or two videos. This is annoying. Thx
-
How to select multiple images and creat new versions???
How do i select 800 images and make new versions of all of them at the same time? I have tried, but it only does the primary one selected and i don't have primary only selected.
-
Hi, Since a few months I've been getting this little pop-up window asking for a name and password to update RSS feeds (see below). This window did not appear before and the problem is that (1) it does not accept my .mac password and (2) I don't know
-
Hi, I would like to know the maximum partition size that Solaris 10 can support/create. We have a Sun StorEdge 6920 system with a 8 TBytes, based on 146 GBytes Hard Disks. Is it possible to create a 4 TBytes partition? if not, any suggestions are app