Doubt in case statement in sql
hiii guruz
i am writing a code in HR schema for case its like this it works fine as i want it to
select commission_pct ,
case
when commission_pct is null
then 'null'
else 'not null' end "comm"
from employees
but when i write+
select commission_pct ,
case commission_pct
when null then 'null'
else 'its not null'
end "chk"
from employees
the o/p that i get is only in every field
its not null
why is it not showing
*'null'*
as it was supposed to show it
thks
oracle 10g
using sql *plus
Similar Messages
-
I am working on a project for ambulance response times. In
the following query which is in my coldfusion code, I am using a
CASE statement on a subquery to count the ambulance response times
in bins. An ambulance should arrive at an emergency incident in
less than 8:59 (539 seconds) or else it is considered late. In my
coldfusion Transact-SQL code I am:
1.) doing a subquery.
2.) counting the 'event numbers' based on the time it took
for the ambulance to arrive.
3.) only counting Lee County ambulances and excluding A6 type
calls (non-emergencies).
4.) grouping it by the dateparts.
SELECT DATENAME("M", I.I_tTimeDispatch) as mths,
(DATEPART("yyyy", I.I_tTimeDispatch)) AS yr,
COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
I.I_tTimeArrival)) BETWEEN 0 AND 539 THEN evnt END) AS OnTime,
COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
I.I_tTimeArrival)) BETWEEN 540 AND 1028 THEN evnt END) AS Late,
COUNT(CASE WHEN (DATEDIFF("S",I.I_tTimeDispatch,
I.I_tTimeArrival)) > 1028 THEN evnt END) AS Outlier
FROM (SELECT I_EventNumber AS evnt, I_tTimeDispatch,
I_tTimeArrival, I_kTypeInfo, I_Agency FROM dbo.IIncident) as I
INNER JOIN dbo.ITypeInfo AS T ON I.I_kTypeInfo =
T.ITI_TypeInfo_PK
WHERE I.I_Agency='LC'
AND T.ITI_TypeID NOT LIKE 'A6*'
GROUP BY (DATEPART("M", I.I_tTimeDispatch)), (DATENAME("M",
I.I_tTimeDispatch)), (DATEPART("yyyy", I.I_tTimeDispatch))
ORDER BY (DATEPART("yyyy", I.I_tTimeDispatch)) ASC,
(DATEPART("M", I.I_tTimeDispatch)) ASC
Here is my problem!
I go into Microsoft Access to verify my statistics and I get
different counts. For instance, in April 2008 my coldfusion query
returns 3,944 on-time ambulance responses. My Access query for the
same time period using only Lee County ambulances and excluding A6
non-emergencies returns only 3,805 responses. This is an undercount
of 139 responses. Even for my other time bins I am getting an
undercount.
Here is my Access SQL for the on time response bin (<539
seconds or 8:59):
SELECT Count(dbo_IIncident.I_EventNumber) AS
CountOfI_EventNumber
FROM dbo_IIncident INNER JOIN dbo_ITypeInfo ON
dbo_IIncident.I_kTypeInfo = dbo_ITypeInfo.ITI_TypeInfo_PK
WHERE (((dbo_IIncident.I_Agency)="lc") AND
((dbo_ITypeInfo.ITI_TypeID) Not Like "a6*") AND
((dbo_IIncident.I_tTimeDispatch) Between #4/1/2008# And #5/1/2008#)
AND
((DateDiff("s",[dbo_IIncident]![I_tTimeDispatch],[dbo_IIncident]![I_tTimeArrival]))
Between 0 And 539));
How could two queries that are supposed to be doing the same
thing return such different results?
To clear up any confusion I am temporarily posting the page.
Please look at it because it may help you visualize the problem.
http://lcfcfn01/Secure/GTandLT_8_59.cfmThank you for your quick reply.
I thought about that, but it isn't what is causing the
discrepancy in the numbers. This is because Access is hitting the
SQL Server through ODBC. The time stamps in SQL Server are ODBC
datetime stamps so they look like this: 4/19/2008 6:20:18 PM
When my query uses the date #5/1/2008# it is like saying May
1, 2008 00:00:00. Please correct me if I am wrong. The query won't
return any results from May 1, 2008 because it stops at zero
hundred hours. I believe it will only go to April 30, 2008 23:59:59
and then stop there.
I do try and play with the date ranges and the 'seconds'
(<539 or >539) parameter and I consistently get different
results from what my coldfusion page is telling me.
David -
in my rpd i got two columns a and b
both have the below mentioned logic
cloumn A : PREIOD <= 20 THEN 'No' ELSE 'Yes' END
column B: PREIOD >20 THEN ‘Yes’ ELSE ‘No’ END
what is the diffrence between these two logic can any one help me with a small example pleaseno diffrence as such.Both will populate same values.what is your requirement?
cloumn A : PREIOD <= 20 THEN 'No' ELSE 'Yes' END It simply states that when value of column period is <=20 then 'No' will be populated for column A and for rest of the values 'Yes' will be populated for column A
column B: PREIOD >20 THEN ‘Yes’ ELSE ‘No’ ENDIt simply states that when value of column period is >20 then 'Yes' will be populated in column B and for rest of the values 'No' will be populated for column B
For further help see the help file.Go to functions Answres and see the case when decription.
Regards,
Sandeep
Edited by: Sandeep Saini on 25-Nov-2010 00:46 -
T-sql case statement in a select
When I execute the following t-sql 2012 statement, the "NO Prod' value is not
being displayed from the sql listed below:
SELECT DISTINCT
IsNull(cs.TYPE,'') as type,
CASE IsNull(Course.TYPE,'')
WHEN 'AP' then 'AP Prod'
WHEN 'IB' then 'IB Prod'
WHEN 'HR' then 'HR Prod'
WHEN '' then 'NO Prod'
END AS label
FROM CustSection cs
INNER JOIN dbo.Person p on P.personID = cs.personID
Left join customCustomer cs564 on cs564.personID = p.personID and
cs564.attributeID ='564'
where ( cs.type is null and cs564.attributeID = null)
or
(cs.type IN ('HR','AP') OR
(cs.type='IB' AND SUBSTRING(cs.code,1,1)='3'))
ORDER BY label
What I want is for 'NO Prod' to be displayed when
cs.type is null and cs564.attributeId is null.
Thus can you tell me how to fix query above so the 'NO Prod' value is displayed in the
select statement listed above?There is no CASE statement in SQL; we have a CASE expression. We do not use the old 1970's Sybase*- ISNULL(); we have COALESCE().
There is no such thing as a magic generic “type” in RDBMS. There is no such thing as a generic “code” in RDBMS. They have to to be “<something in particular>_type” and “<something in particular>_code” in a valid data model. How about blood_type
and postal_code??
There is no such thing as a generic “person” table in RDBMS. First of all, do you really have only one person, as you said?? But the important point is that these persons play a role in the data model – customers, students, etc. You are doing the wrong thing
and doing it badly. This table should not exist any more than a table of “Things” such exist.
And the reason you are beyond any real help is “attribute_id” which tell us that your schema is a total disaster of data and meta data mixed together in a non-RDBMS written in awful SQL. Based on cleaning up bad SQL for 30 years, it looks like you are an OO
programmer who never unlearned his prior mindset.
Why did you allow an encoding schema with blanks? Why do you have so many NULL-able columns?
SELECT DISTINCT is very rare in a properly designed schema. The DRI references assure that rows cam be matched. To get you started, look at this skeleton:
CREATE TABLE Products
(product_gtin CHAR(15) NOT NULL PRIMARY KEY,
product_type CHAR(2) DEFAULT 'XX' NOT NULL
CHECK (product_type IN ('AP', 'IB', 'HR', 'XX'))
The table name is a plural noun because it models a set (NOT an OO class).
The GTIN is an industry standard identifiers, and not have to invent our own.
The product_type (not blood_type, not automobile_body_type!) has a constraint that assures it is never NULL and never blank; I invented 'XX' as a default.
You need more help than you can get in a forum, but if you will follow Netiquette and post the DDL, we can get you started.
--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 -
Sql 2008 nested case statement
I have a question about understanding nested case statements in sql server 2008:
The sql looks like the folloiwng:
select numberofcases
from inventory
where inventory_cnt > 1000
(when select top 1
from inventory
where inventory_cnt > 750
then numberofcases = 750 * 30
when select top 2
from inventory
where inventory_cnt > 975
then numberofcases = 975 * 35
when select top 3
from inventory
where inventory_cnt > 1025
then numberofcases = 1025 / 10
when select top 4
from inventory
where inventory_cnt > 1050
then numberofcases = 1050 / 5) c * 2
as casesused, select CustomerNumber from inventory
I would like you to explain the following:
1. There are 4 when statements. Will the logic hit each when statemnet or will the logic
stop once the first when statement is true?
2. Would you explain what the c* 2 means from the school listed above?Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums.
SELECT CASE
WHEN Inventory_cnt > 1050 THEN 1050 / 5
WHEN Inventory_cnt > 1025 THEN 1025 / 10
WHEN Inventory_cnt > 750 THEN 750 * 30
WHEN Inventory_cnt > 975 THEN 975 * 35
ELSE NULL END AS cases_used
FROM Inventory;
I would like you to explain the following:
>> 1. There are 4 when statements. Will the logic hit each when statement or will the logic stop once the first when statement is true? <<
This code is garbage, not SQL. CASE is an expression, not a statement. Expressions return a scalar value. Your are trying to do control flow! And the answer is that a CASE works this way
1) look at the THEN clauses and determine the data type to use
2) test each WHEN clause and execute the first one that tests TRUE in left to right order.
>> 2. Would you explain what the c* 2 means from the school listed above? <<
Syntax error and more garbage code.
--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 -
Can CR 2008 with XML ODBC driver using SQL CASE statement?
Hi:
when i use SQL Command to provide data to the report from XML file connection. I can not use CASE statement , CR always has error message about "CASE" word.
I test the same Statement in SQL client connected to Oracle, it runs fine.
So.. Is it driver's limitation that XML datasource can not use CASE statement inside SQL command window?
Thanks anyone's reply in advance.
JohnnychiHi Johnny,
CR supports what every the ODBC driver supports. The error you are getting is from the XML driver, CR is just passing it through.
Try using an ODBC to XML driver and then a stand-alone ODBC test tool to see if your SQL works.
If not you'll have to find another way to use the CASE statement.
Thank you
Don -
Hi,
could you please advise how to add below New case to below Main case
New case:
when (convert(varchar,date,101) >= '01/01/2014' OR qtr >= '14Q1') then
case when PP='ABC' and pl='EFG' then Revenue*.552
else 0 end
Main case:
SUM(
case
when ((convert(varchar,date,101)>= '09/19/2013' and qtr = '13Q3') OR qtr >= '13Q4') then
case when PP='ABC' and pl='EFG' then Revenue*.542
else 0 end
when (convert(varchar,date,101) < '09/19/2013' OR qtr < '13Q3') then
case when PP='ABC' and pl='EFG' then Revenue*.501
else 0 end
else 0 end) revenue,There is no CASE statement in SQL; we have CASE expression. AND you got the syntax wrong. SQL uses the ISO-8601 date format; it is one of the most basic ISO Standards on Earth AND you should know it. But worse than that, you are still using the 1970's
Sybase CONVERT string function! NO! Did you know that DATE is a reserved word in SQL AND cannot be a column name?
When we design a code for temporal units like Quarters, we follow the ISO-8601 as closely as possible. That means a full four-digit year.
Since you were rude AND did post DDL, I will guess that your improper “date” is a TIMESTAMP (aka DATETIME or DATETIME2(n) in Microsoft dialect).
>> could you please advise how to add below New CASE to below Main CASE <<
I never heard the term “main CASE”, even when I voted on this feature. Can you explain it to me and show where I missed it?
The quarters are temporal computations; we would not put them in a base table, but a good SQL programmer would use a VIEW with a join to a report period table.
CASE WHEN CAST (foobar_timestamp AS DATE) >= '2014-01-01'
OR foobar_qtr > = '2014Q1'
THEN CASE WHEN pp = 'ABC'
AND pl = 'EFG'
THEN something_revenue * 0.552
ELSE 0.000 END;
I will assume that pl and pp well-understood terms in your industry and not improper data element names. Why did you nest CASE expressions? Let me answer that: you think that CASE is IF-THEN-ELSE statements!
Did you notice that an event during '2014Q1' is always BETWEEN '2014-01-01' AND '2014-03-31'? So this is redundant!
A minor point, it is good idea to use a leading zeroes and decimal zeroes to show the guy maintaining code what he is working with. It also helps the compiler avoid casting. Your expression also has no name.
CASE WHEN CAST (foobar_timestamp AS DATE) > = '2014-01-01'
AND pp = 'ABC'
AND pl = 'EFG'
THEN something_revenue * 0.552
ELSE 0.00 END AS nameless_floob;
I am afraid that you might have re-discovered the Algol-60 dangling ELSE problem. As with Algol-60, the ELSE in SQL associates with the nearest CASE. Not with the outermost CASE.
Your expression ought to have this skeleton:
SUM(CASE WHEN ???
THEN something_revenue * 0.542
WHEN ???
THEN something_revenue * 0.501
WHEN ???
THEN something_revenue * 0.552
ELSE 0.000 END)
AS something_revenue_tot
--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 -
I want to do something like this in a SELECT where I set the value of one field based on another. Is this possible. If not are there any alternatives? Thanks
CASE WHEN [var_cpnt_brkpt_ct] = '0' THEN [enrc_cpnt_var_price_rt] = '0'There is no CASE statement in SQL; we are a declarative language. We have a case expression! There is no control flow, like you are trying to write. You do not even know that fields are columns. This is as silly
as asking for the color the feathers on a fish.
--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
Thank you for your support. Good day Sir. -
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 -
What is the syntax for a CASE statement in Crystal XI
I'm having difficulty locating documentation for the use of CASE statements in Crystal syntax. My database administrator does not allow me to write SQL expressions so I need to covert the SQL below to Crystal Syntax. Can anyone help me? Thank you very much!!
Select
CASE
WHEN projects.ProjType like 'S%' then 'Shopping Center'
WHEN projects.ProjType like 'I%' then 'Industrial'
WHEN projects.ProjType like 'O%' then 'Office Building'
ELSE 'Other'
END
from projectsLet's assume column XYZ has both numbers (1), and letters (any alphabet).
I have a case statement on SQL to turn any value that's not 1 into 0, then I am getting a sum of that column.
I am also grouping by Row A, B etc to get aggregated sum of column XYZ for those group.
Now on Crystal Reports function, I need to sum up values under column XYZ for all the groups.
If I try using sum function like below, I get an error stating:
"A number field or currency amount field is required here"
(sum({Command.XYZ}))
So I thought if I can use a case statement to change the non-numbers to 0 prior to sum that will probably resolve it. But I could not get the below case statement to work either (Error: A string is required).
SELECT {Command.XYZ}
Case 1:
1
Default:
0; -
How to create nested CASE statements in PL/SQL
Can anyone please tell how to create Nested CASE statements in PL/SQL with proper syntax?
It would be better if you can help with an example.
Thank you!Something like this:
SQL> set serveroutput on
SQL> declare
2 v1 number := 2;
3 v2 varchar2(1) := 'C';
4 begin
5 case v1
6 when 1 then dbms_output.put_line('First');
7 when 2 then begin
8 case v2
9 when 'A' then dbms_output.put_line('Found A');
10 when 'B' then dbms_output.put_line('Found B');
11 when 'C' then dbms_output.put_line('Found C');
12 else dbms_output.put_line('NONE');
13 end case;
14 end;
15 else dbms_output.put_line('Else');
16 end case;
17 end;
18 /
Found C
PL/SQL procedure successfully completed
SQL> If you have further doubts regarding syntax you can read the docs on the Case statement here:
http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/case_statement.htm -
SQL Expression in decode function or case statement?
Can I put SQL expressions in decode function or case statement?
For example,
select le.profile, decode( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile, 0, 'N', 'Y')
from element le;
or
select le.profile, case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0 THEN 'N'
ELSE 'Y'
from element le;
None of the above work.
Can anyone tell me how to make it work?
Is there any workaround?
Thanks,
JYou simply needed and END to your CASE statement;
SQL> with profile_data as (
select 'XXXX_AFTER' name, 1 object_id from dual),
element as (
select 1 profile from dual union all
select 2 from dual)
select le.profile,
case WHEN ( select count(1) from profile_data where NAME= 'XXXX_AFTER' and object_id = le.profile) = 0
THEN 'N'
ELSE 'Y'
END new_col
from element le
PROFILE N
1 Y
2 N -
Hi PL/SQL experts,
I'm going a bit loopy here, so could someone please point out what I'm doing wrong with this case statement:
Test procedure is:
CREATE OR REPLACE procedure SCOTT.postcode_validate_2 (input_post_code VARCHAR2) as
alphabet_string VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxwyz';
number_string VARCHAR2(10) := '012345789';
last_part_postcode VARCHAR2(3) := NULL;
BEGIN
IF INSTR(input_post_code,' ') = 0
THEN
DBMS_OUTPUT.PUT_LINE('We need a space in the postcode please');
GOTO exit;
ELSIF LENGTH(SUBSTR(input_post_code,instr(input_post_code,' ')+1)) > 3
THEN
DBMS_OUTPUT.PUT_LINE('Last part of postcode can only be 3 characters');
GOTO exit;
ELSE
last_part_postcode := SUBSTR(input_post_code,instr(input_post_code,' ')+1);
END IF;
CASE input_post_code
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 2
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A99')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9A')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9A');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(number_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA99')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(alphabet_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9A')
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9A');
-- GOTO exit;
-- END IF;
END;
-- Check last part of format, should be AA9
IF (instr(number_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the correct format, 9AA');
ELSE
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the wrong format!');
END IF;
<<exit>>
DBMS_OUTPUT.PUT_LINE('Please try again');
END;
However, I'm getting the following error:
LINE/COL ERROR
37/6 PLS-00103: Encountered the symbol "WHEN" when expecting one of
the following:
:= . ( % ;
On a second note, can I not have the ELSE structure embedded within the case (currently commented out)?
Thanks very much in advance.
DevFixed code:
CREATE OR REPLACE procedure postcode_validate_2 (input_post_code VARCHAR2) as
alphabet_string VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxwyz';
number_string VARCHAR2(10) := '012345789';
last_part_postcode VARCHAR2(3) := NULL;
BEGIN
IF INSTR(input_post_code,' ') = 0
THEN
DBMS_OUTPUT.PUT_LINE('We need a space in the postcode please');
GOTO exit;
ELSIF LENGTH(SUBSTR(input_post_code,instr(input_post_code,' ')+1)) > 3
THEN
DBMS_OUTPUT.PUT_LINE('Last part of postcode can only be 3 characters');
GOTO exit;
ELSE
last_part_postcode := SUBSTR(input_post_code,instr(input_post_code,' ')+1);
END IF;
CASE
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 2
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A99');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 3
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(number_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format A9A');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format A9A');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(number_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA99');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA99');
-- GOTO exit;
-- END IF;
WHEN (length(substr(input_post_code,1,instr(input_post_code,' ')-1)) = 4
AND instr(alphabet_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(number_string,substr(input_post_code,3,1)) != 0
AND instr(alphabet_string,substr(input_post_code,4,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('We have a valid postcode in the format AA9A');
-- ELSE
-- DBMS_OUTPUT.PUT_LINE('Sorry but that is an incorrect postcode! Format AA9A');
-- GOTO exit;
-- END IF;
END CASE;
-- Check last part of format, should be AA9
IF (instr(number_string,substr(input_post_code,1,1)) != 0
AND instr(alphabet_string,substr(input_post_code,2,1)) != 0
AND instr(alphabet_string,substr(input_post_code,3,1)) != 0)
THEN
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the correct format, 9AA');
ELSE
DBMS_OUTPUT.PUT_LINE('End part of the postcode is in the wrong format!');
END IF;
<<exit>>
DBMS_OUTPUT.PUT_LINE('Please try again');
END;
/As VG2 pointed out you were missing some semicolons.
Also, CASE input_post_code was replaced with just CASE since you are doing a searched case.
Also, END at the end of the case statement was replaced with END CASE. -
Case statement in advanced sql
how to use case statement in advanced sql.Example if quarter=1 i need to select jan,fev,and march months from table
this is the case statement i am using :
case when 1=@{quarter} then substring(cast((etxnmis.month_year) as char) from 5 for 2) IN ('03', '04', '05') else null end
and i get the below error
: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27002] Near <IN>: Syntax error [nQSError: 26012] . (HY000) -
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.
Maybe you are looking for
-
Dear SAP Experts, How to configure a scenario where : 1 Scene: Sales without free goods: Earlier company was selling a shaving cream 150gms for 100 INR (MRP) and was paying some 10% tax to government. 2 Scene: Sales with free goods: Now company wants
-
Magic Mouse Middle Click Problem on Bootcamp Windows 7
Hi, I am using Windows 7 on my MacBook Pro via Bootcamp. My magic mouse working good but I need middle click for some design softwares. I found some softwares can simulate middle click but the softwares just running under Mac OS. Are there any Window
-
Transaction Codes for Report Painter Reports
Hi, Can any bodu assist on how can we create a link for the report painter report and the transaction code for the same. Also is there somthing to be taken care while getting the same transported to another client. Thanks & Regards, Ankur Goel
-
Will 1.5 compiler tag default constructor as synthetic?
Hi, This is a question about the synthetic attribute for the default constructor. This attribute has been added at the moment the inner classes have been introduced in the language. I think its purpose is to distinguish methods added by the compiler
-
How do I revert back to Mac OSX 10.7.4
Hi I having problem tethering my Canon camera to my macbook pro with latest software update 10.7.5 . How do I revert back to 10.7.4 ? Apple should really work closely with the major Camera manufacturers like Canon , Nikon and Phaseone before comin