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

Similar Messages

  • SQL CASE statement in XML template- End tag does not match start tag 'group

    Hi All,
    I am developing a report that has the SQL CASE statement in the query. I am trying to load this into RTF with report wizard and it gives me below error
    oracle.xml.parser.v2.XMLParseException: End tag does not match start tag 'group'
    Does XML publisher support CASE statement?
    My query is something like this
    SELECT customercode,
    SUM(CASE WHEN invoicedate >= current date - 30 days
    THEN balanceforward ELSE 0 END) AS "0-30",
    SUM(CASE WHEN invoicedate BETWEEN current date - 60 days
    AND current date - 31 days
    THEN balanceforward ELSE 0 END) AS "31-60",
    SUM(CASE WHEN invoicedate < current date - 60 days
    THEN balanceforward ELSE 0 END) AS "61>",
    SUM(balanceforward) AS total_outstanding
    FROM MyTable
    GROUP BY customercode
    ORDER BY total_outstanding DESC
    Please advice if the CASE statement or the double quotes are causing this error
    Thanks,
    PP

    I got this to work in the XML but the data is returning zeros for all the case statements. When I run this in toad I get results for all the case conditions but when ran in XML the data displayed is all zeros. I am not sure what I am missing. Can someone shed some light on this please
    Thanks!
    PP

  • CASE Statement in a SELECt

    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.

  • PL/SQL - Case Statement

    Hello, just starting to learn PL/SQL. I have a query which runs just fine and it has a case statement. When I take that query and place it into a procedure and compile, it gives me a compile error stating "ENCOUNTERED symbol CASE when expecting... providing a list of symbols.
    This procedure is part of a package, so I am only showing the procedure portion...
    PROCEDURE QRY_USERS (oRows                     OUT t_cursor)
    IS
    BEGIN
         OPEN o_Rows FOR
         select ou.User_id,
                   ou.AD_Login_ID,
                   ou.First_name,
                   ou.Last_Name,
         oct.CODE_DESC,
                   case when ou.deleted is null then 'N'
                   else 'Y' end Deleted
         from tst_ops_users ou, tst_ops_code_tbl oct
         where oct.CODE_TYPE ='USER_TYPE'
              and oct.code_name = ou.USER_ROLE_TYPE;
    END QRY_USERS;
    So is there some different syntax with case statements or is there some other erro causing this?
    Thanks a bunch for your assistance!!!

    Which version of the database are you working on? In 8i the PL/SQL engine did not support the use of CASE in SQL statements (along with a whole bunch of other fresh additions to SQL syntax).
    If that is your problem you could try this, which ought to use the SQL engine instead...
    PROCEDURE QRY_USERS (oRows OUT t_cursor)
    IS
    BEGIN
    OPEN oRows FOR
    'select ou.User_id,
    ou.AD_Login_ID,
    ou.First_name,
    ou.Last_Name,
    oct.CODE_DESC,
    case when ou.deleted is null then ''N''
    else ''Y'' end Deleted
    from tst_ops_users ou, tst_ops_code_tbl oct
    where oct.CODE_TYPE =''USER_TYPE''
    and oct.code_name = ou.USER_ROLE_TYPE';
    END QRY_USERS;although you can obviate the need for CASE by using either DECODE or NVL2...
    nvl2(ou.deleted , 'Y', 'N') AS deletedCheers, APC

  • SQL Case statement Help....

    Hi , I have to Compare two columns to see if they are matching or not....and give the count() of overrides if they are not matching/
    I have got that with the below SQL:
    Count of Overrides =
    select count(Case when Col_1 != Col_2 then 1 else null end) Overrides
    from table_1, table_2
    where table_1.id = table_2.id
    But now i have to look at two columns and get the count()
    I have
    col_1 and col_2 in table_1 and
    col_3 and col_4 in table_2
    (I have to compare col_1 with col_2 and...... col_3 with col_4 and if either of them is not matching.... count it as an override
    Will the following SQL return correct values?
    Count of Overrides =
    Select
    Count( Case when (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end) Overrides
    from table_1, table_2
    where table_1.id = table_2.id
    Thanks

    "yes, it can be rewritten as a decode. but why bother?"
    Well, although I do like Sy's code better, the decode version does naturally handle NULLs unlike the case.
    SQL> WITH t AS (
      2     SELECT 1 col_1, 1 col_2, 2 col_3, 2 col_4 FROM dual UNION ALL
      3     SELECT 1, 1, 2, 3 FROM dual UNION ALL
      4     SELECT 1, 2, 3, 3 FROM dual UNION ALL
      5     SELECT null, 1, 2, 2 FROM dual UNION ALL
      6     SELECT 1, 1, 2, null FROM dual UNION ALL
      7     SELECT 1, 2, 3, 4 FROM dual)
      8  SELECT col_1, col_2, col_3, col_4,
      9         CASE WHEN (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end Ocase,
    10         DECODE(col_1, col_2, DECODE(col_3, col_4, NULL, 1), 1) odecode
    11  FROM t;
         COL_1      COL_2      COL_3      COL_4      OCASE O
             1          1          2          2
             1          1          2          3          1 1
             1          2          3          3          1 1
                        1          2          2            1
             1          1          2                       1
             1          2          3          4          1 1John

  • Sql case statement with link not opening new window

    Apex 4.2
    I am writing a query that has a case statement. I need the case statement to open up a new window, not a new tab. I have the following:
    SELECT
    case when SCHED_ID = 1 then
    '<a href="javascript:popupURL(''http://www.google.com'')">LINK</a>'
    end as MyLink
    FROM Table_Name
    When I plug this into a a column link in the URL field under a page item or report item, then a popup window appears. However, inside the query I am getting a new tab.
    ANy help on this matter would be great. Thanks in advance.

    Hi,
    Try adding a target attribute to you link:
    '<a href="javascript:popupURL(''http://www.google.com'')" target="_blank">LINK</a>' 
    Regards,
    Vincent

  • 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.
    Johnnychi

    Hi 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

  • SQL Case Statement

    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

  • SQL Case Statement Problem with Maxdb

    Hello,
    I'm running a J2E application on Netweaver AS. I have on problem that I just cannot figure out.
    The statement works in SQL Studio but when I try to code it it does not work at all.
    select COLA, SUM(CASE WHEN COLB=10 THEN 1 ELSE 0 END) from TABLE group by COLA
    When executed as statement in Java I get:
    Error [javax.servlet.ServletException: java.lang.IllegalStateException: illegal stack size: 4
    contents:
    com.sap.sql.tree.SelectStatement
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.ComparisonPredicate], with root cause [java.lang.Exception: java.lang.IllegalStateException: illegal stack size: 4
    contents:
    com.sap.sql.tree.SelectStatement
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.IntegerLiteral
    com.sap.sql.tree.ComparisonPredicate].
    Any thoughts on that? Thanks!
    Edited by: MD on Feb 18, 2009 7:37 PM

    Hi MD,
    with SQL Studio you mean you work with MaxDB?
    Are you sure you're working directly on MaxDB and not with OpenSQL? (That's different!)
    If you want the first, try setting SQL type "vendor" or "native sql". In such case you have to define a new custom datasource through configuration. How that works depends on the version you are using.
    Try to find out what the actual error message is. The stack trace is not enough. There should be more.
    Regards,
    Benny

  • SQL CASE STATEMENT IMPLEMENTATION

    REquirment
    • Add indicator to the end of the files, (position 1051 in both extracts, either have value of Y or N).
    o DUAL COVERAGE (Y/N)
    • Logic to determine indicator values from Member Eligibility Table:
    o For ‘Y’ indicator:
    o When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID = ‘MD11’ (Mean Dual covered member)
    o For ‘N’ indicator:
     When dbo. CMC_MEPE_PRCS_ELIG.CSCS_ID <> ‘MD11’
    • Groups included:
    o 100100 (Medicare)
    o 100598 (Medicaid-OHP)
    • Previous syntax
    • select top 20000
    • EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
    • RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
    • a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
    • YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
    • S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
    • P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
    • BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
    • b.HIOS_NUMBER,
    • null as PREMIUM_PAID_DATE,
    • null as PREMIUM_PAID_END_DATE,
    • b.APTC,
    • null as 'GracePeriodIndicatorStartDate',
    • null as'GracePeriodIndicatorEndDate',
    • null as'ExchangePlanType'
    • from Extract_602_603_PBH_Extract_Main a
    • left join Extract_602_603_PBH_Extract_HRI b
    • on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
    Syntax I am trying to implement(taking forever to execute) Please help correct
    select distinct
    EXT_DATE,SUPPLIER_NAME,BUSINESS_UNIT,PROG_NO,PG_DESC,DIVISION_NO,RISKPOP_MEDICARE_EVENT_CODE,
    RISKPOP_MEDICAID_AID_CATEGORY,MEMBER_NO,MEDICARE_NO,MEDICAID_NO,LASTNAME,MIDINITIAL,FIRSTNAME,YMDBIRTH,
    a.SEX,CLASS,CL_DESC,S_LASTNAME,S_MIDINITIAL,S_FIRSTNAME,S_DOB,S_SEX,BENFIT_PKG,BEN_PKG_DESC,CLASS_ID,PLAN_ID,
    YMDEFF_BP,YMDEND,REASON,PRIME_SECOND,PHP_DUAL,S_ADDRESS1,S_ADDRESS2,S_ADDRESS3,S_CITY,S_STATE,S_ZIP,S_COUNTRY,
    S_PHONE,M_ADDRESS1,M_ADDRESS2,M_ADDRESS3,M_CITY,M_STATE,M_ZIP,M_COUNTRY,M_PHONE,DIV_NAME,PROV_NO,IRS_NO,
    P_LASTNAME,P_FIRSTNAME,P_MIDINITIAL,YMDEFF_PCP,ALT_KEY,ALT_CARRIER_NO,ALT_CARRIER_FUL,ALT_YMDEFF,ALT_YMDEND,
    BENFIT_PKG_EFF,BENFIT_PKG_TERM,a.MEME_CK,
    b.HIOS_NUMBER,
    null as PREMIUM_PAID_DATE,
    null as PREMIUM_PAID_END_DATE,
    b.APTC,
    null as 'GracePeriodIndicatorStartDate',
    null as'GracePeriodIndicatorEndDate',
    null as'ExchangePlanType',
    case when MEPE.CSCS_ID = 'MD11' AND grgr.GRGR_ID IN('100100','100598')
    THEN 'Y'
    ELSE 'N' end as DualCoverageIndicator
    from Extract_602_603_PBH_Extract_Main a
    left join Extract_602_603_PBH_Extract_HRI b
    on LEFT(a.MEMBER_NO,7) = b.SBSB_ID
    join FacetsReport.dbo.CMC_MEPE_PRCS_ELIG MEPE
    ON a.CLASS_ID= MEPE.CSCS_ID
    Join FacetsReport.dbo.CMC_GRGR_GROUP grgr
    ON MEPE.GRGR_CK= grgr.GRGR_CK

    >on LEFT(a.MEMBER_NO,7)
    =b.SBSB_ID
    This is not a good JOIN. It is not SARGable:
    http://www.sqlusa.com/bestpractices/sargable/
    Can you post table/index DDL? Thanks.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Custom SQL CASE Statement

    Hello All,
    I have a query similar to the one below. I have to use a Custom SQL DB adapter to achieve this. When i create a variable I get four variables in the input payload (two for Param1 and two for Input). I was wondering if we can avoid this, because this is like duplicity and we have to populate the values twice each (I know this can be achieved by a Procedure, but we have a restriction).
    SELECT CASE
    WHEN #param1 = 'P1'
    THEN (SELECT col1
    FROM table1
    WHERE col2 = #input)
    END column1,
    CASE
    WHEN #param1 = 'P2'
    THEN (SELECT col1
    FROM table2
    WHERE col2 = #input)
    END column2,
    FROM DUAL;
    The input collection is as shown below.
    <xs:complexType name="compiste_queryInput">
    <xs:sequence>
    <xs:element name="param1" type="xs:string" nillable="true"/>
    <xs:element name="input" type="xs:string" nillable="true"/>
    <xs:element name="param1" type="xs:string" nillable="true"/>
    <xs:element name="input" type="xs:string" nillable="true"/>
    </xs:sequence>
    </xs:complexType>
    Any help is much appreciated.
    Thanks
    Krishna

    Hi Krishna,
    I think this is a limitation. Actually it creates an element in xsd for each bind parameter and won't allow having 2 elements with the same name inside the xsd.
    The one given by you also will report a compile time error as it is using #param1 and #input twice.
    You need to change them to param1, param2 etc. and copy the same values to each.
    Appreciate if anyone can post a workaround for the same.
    Regards,
    Neeraj Sehgal

  • Sql case statement for parametes

    I am using sort parameters in the stored procedure
    the following is my case statment
    CASE When @SORT_1 = 'CUSTOMER'
                     Then ar_ivhdr_tbl.EN_CUST_KEY
                     When @SORT_1 = 'BILLTO'
                    Then ar_bill_tbl.ar_bill_name
                     Else ' ' END SORTKEY
    what i would like to do is
    have the sort key sort by 2 fields so instead of just the customer sort sorting the customer field
    i would like it to sort customer and bill to
    this is the syntax i tried but sql doesnt like it
    CASE When @SORT_1 = 'CUSTOMER'
    Then ar_ivhdr_tbl.EN_CUST_KEY,ar_bill_tbl.ar_bill_key
    When @SORT_1 = 'BILLTO'
    Then ar_bill_tbl.ar_bill_name, date
    Else ' ' END SORTKEY
    syntax issues, any ideas?

    Hi Sharon,
    Your syntax is off.  Not sure what database you are using by it should look something like:
    CASE @SORT_1
    When 'CUSTOMER' Then ar_ivhdr_tbl.EN_CUST_KEY,ar_bill_tbl.ar_bill_key
    When 'BILLTO' Then ar_bill_tbl.ar_bill_name, date
    Else ' '
    END
    Good luck,
    Brian

  • Nested CASE Statements in my SELECT of Query not calculating correctly

    Hi - Am doing simple query to calculate statistics on students per course, the WHERE includes a parameter for Academic Year, so need If Academic Year = x then calculate age in the 1st Sept of that Year, then count number of 19Yrs&Over. Have included my successful lines for sum of other data, in my CASE the calculations are not distinguishing whether age is over or under 19 just counting all. Presume is problem with Date calculation or CASE?? Runs without error..I'm guessing I can nest a CASE?!
    Many thanks!
    SELECT ......
    various fields bought through then
    count(p.PERSON_CODE) All_Enrolments,
    sum(DECODE(ru.FES_PROGRESS_CODE,'ACT',1,0)) Active,
    sum(DECODE(ru.FES_PROGRESS_CODE,'WNS',1,0)) NonStarter,
    sum(DECODE(ru.FES_PROGRESS_CODE,'WTH',1,0)) Withdrawn,
    sum(DECODE(ru.FES_PROGRESS_CODE,'TRN',1,0)) Transfers,
    sum(DECODE(la.completion,'2',1,0)) Completed,
    sum(DECODE(la.outcome,'1',1,0)) Achieved,
    sum(DECODE(p.sex,'F','1','0')) Female,
    sum(DECODE(p.sex,'M','1','0')) Male,
    SUM(
    CASE
    WHEN uio.CALOCC_OCCURRENCE_CODE='04'
    THEN
    CASE
    WHEN ((to_date('01-08-2004','dd-mm-yyyy')-to_date(p.date_of_birth,'dd-mm-yyyy'))/365.25)<'19'
    THEN '0'
    ELSE '1'
    END
    WHEN uio.CALOCC_OCCURRENCE_CODE='05'
    THEN
    CASE
    WHEN ((to_date('01-08-2005','dd-mm-yyyy')-to_date(p.date_of_birth,'dd-mm-yyyy'))/365.25)<'19'
    THEN '0'
    ELSE '1'
    END
    WHEN uio.CALOCC_OCCURRENCE_CODE='03'
    THEN
    CASE
    WHEN ((to_date('01-08-2003','dd-mm-yyyy')-to_date(p.date_of_birth,'dd-mm-yyyy'))/365.25)<'19'
    THEN '0'
    ELSE '1'
    END
    ELSE '0'
    END ) Over19sInc19
    FROM .......

    you can use this formula to check on the age:
    TRUNC(MONTHS_BETWEEN(to_date('01-08-2004','dd-mm-yyyy'),to_date(p.date_of_birth,'dd-mm-yyyy'))/12)hope this helps.

  • 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)

  • Using Case statement to insert,update,delete  the tables

    Hi All,
    I have to check the databse ,
    if it is developement then
    insert/update/delete values in tables;
    if it staging then
    insert/update/delete values in tables;
    if it is production then
    insert/update/delete values in tables;
    thers is function available to check the current database
    For doing the about i am trying to write CASE statement like this
    SELECT function,
    case
    when fun = 'developement' then insert into table1 values ('abcd','1234')
    when fun = 'staging' then insert into table1 values ('abcd','1234')
    when fun= 'production' then insert into table1 values ('abcd','1234')
    else null
    from dual
    its throughing me an error
    please help
    Thanks,

    Hi,
    You can use CASE staement any place where an expression is expected.
    For example, in:
    UPDATE  table_a
    SET     col1 = exp1
    ,       col2 = exp2
    WHERE   exp3 = exp4;all the expressions are labled lke expn.
    Note that table_a, col1 and col2 are not expressions: you must hard-code these names, or use dynamic SQL.
    So it's okay to say:
    UPDATE  table_a
    SET     col1 = CASE
                       WHEN  db = 'development'  THEN  0
                       WHEN  db = 'staging'      THEN  1
                   END
    ,       col2 = CASE
                       WHEN  db = 'development'  THEN  NULL
                       WHEN  db = 'staging'      THEN  col2
                   END
    WHERE   db != 'production';In this example:
    in the development database, col1 is set to 0 and col2 is set to NULL
    in the staging database, col1 is set to 1 and col2 is unchanged (that is, set to what it already was)
    in the production database, nothing is changed (the WHERE condition is always FALSE)

Maybe you are looking for

  • Hirerachical display in ALV report

    Hi all, I am using Fm as following for hirerachical display. CALL FUNCTION 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'     EXPORTING       i_interface_check        = ' '       i_callback_program       = sy-cprog       is_layout                      = ls_layout

  • Error message: package Jfxcore does not exist

    I have a file "Jfxcore.jar" in C:\Project. I added C:\Project\Jfxcore.jar to the classpath ( in xp control panel). My app, test1, has the line: import Jfxcore.*; It is also located in C:\Project when I compile from the commad line with : javac test1.

  • Howto use formula columns in matrix reports

    Hello How can i use a formula column in matrix report whose function would be Formula_Column_Result=A-B where A=Cell A B =Cell B Regards Fahad

  • What happened to over the air updates

    am I the only one, or has over the air updates been changed to over WiFi updates? Not the same thing. Pretty inconvenient when you're somewhere without WiFi and want to update your phone.

  • Import DVDs to iMovie

    I want to import footage from DVDs into iMovie. DVDs are of legislative sessions, not commercial movies. How can I do this? Thanks.