PL/SQL block to sql case

Hello,
I have a newbie sql question:
I have the following pl/sql block that I want to transform in sql case code:
             IF Num_WholesaleNonDiscountValue > 0.0 THEN
                  UsageStatus := 'CHARGE';
                  if Num_WholesaleNonDiscountValue < 1.0 then
                      WholesaleNonDiscountValue := '0' || TO_CHAR(Num_WholesaleNonDiscountValue);
                    else
                      WholesaleNonDiscountValue := TO_CHAR(Num_WholesaleNonDiscountValue);
                  end if;
              ELSE
                  UsageStatus := 'FREE';
                  WholesaleNonDiscountValue := TO_CHAR(Num_WholesaleNonDiscountValue);
              END IF;All I do is the following code:
select (case when Num_WholesaleNonDiscountValue > 0.0 then
                          (case Num_WholesaleNonDiscountValue < 1.0 then  '0' || TO_CHAR(Num_WholesaleNonDiscountValue
                           else TO_CHAR(Num_WholesaleNonDiscountValue))
         else TO_CHAR(Num_WholesaleNonDiscountValue)) from table_name;I do not know how to evaluate the UsageStatus variable, where to put it in the select statement.
This is for my learning process.
Thanks in advanced,
Dan
Edited by: danut68 on Jan 13, 2010 5:52 AM

Hi, Dan,
I think you want something like this:
SELECT     CASE
          WHEN  Num_WholesaleNonDiscountValue > 0
          THEN  'CHARGE'
          ELSE  'FREE'
     END                              AS UsageStatus
,     CASE
          WHEN  Num_WholesaleNonDiscountValue > 0
          AND   Num_WholesaleNonDiscountValue < 1
          THEN  '0'
     END || TO_CHAR (Num_WholesaleNonDiscountValue)     AS WholesaleNonDiscountValue
FROM     table_x
;A CASE expression returns one value.
In PL/SQL, you can do two or more completely separate things (set two different variables, for example) in the same IF-THEN-ELSE block.
To get the same results in SQL requires a completely different approach.
The clearest is to use a different CASE expression for each of the things you're trying to do, as I did above. The WHEN clauses of those CASE statements may be very similar, even identical.
Sometimes you can factor out some of the logic (using a sub-query, perhaps) so that the logic that has to be repeated in each CASE expression is very simple.
Another option for setting two variables is to have a single CASE expression that returns a string wihich is the concatenation of two different varibales, which you later parse into two separate variables. I would do this only as a last resort.

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

  • Looking for good pl/sql case studies/hands on exercises

    Hi there,
    I am new to plsql. Looking for some good pl/sql case studies/hands on exercises/small prototype project etc to learn the basic nitty-gritty.
    Can anybody please help?
    Many Thanks,
    Avishek

    this page http://itcareershift.com/blog1/2010/11/15/plsql-exercises/ contains different types of sql statements used inside pl/sql..when you say case studies do you mean examples for each and every concept of pl/sql starting from stored procedures , packages , functions, triggers , collections etc?

  • Invoice Block in all cases

    Hi to all
    I need some help for an issue.
    The problem is that all invoice posted via MIRO are blocked, even Invoice it's higher, lower or equal to the PO or GR... it's blocked in all cases...
    But isn't all, because the strange thing it's that this Invoice Block happen in one Plant of the Company Code, only in that....so, I can't find a Config where I can set tolerances for CoCd and Plant....
    I made a change, and modify the tolerances config of the CoCd like other ones, but the problem still happen only in that Plant of that CoCd...
    Hope you can help me with this...
    Regards

    Hi
    Tks for the answer
    I made some changes in the tolerances, and I got no block for payment for Invoice with amount equal to PO, but in cases that I put amount superior or inferior, just do not post or block the invoice... and in this case should post and block.
    Any other ideas? Tks!!

  • Help needed in writing SQL CASE or DECODE statement

    Hi experts,
    I need to write a SQL to select order_num, cntry_cde, prod_id and Qty by joining order_num on PROD_ORDER and PROD_ORDER_TXT.
    Here is my sample data
    PRODORDER_               
    order_num     cntry_cde     Prod_id     Qty
    100     US     A1     5
    101     US     A2     10
    102     AU     A3     4
    103     AU     A4     9
    104     IN     A5     3
    PRODORDER_TXT_               
    order_num     cntry_cde     Prod_id     
    100     US     A1     
    101     US     A2     
    102     NZ     A3     
    103     AU     A4     
    104          A5     
    Here is the requirement,
    1) If the cntry_cde in PROD_ORDER is same as cntry_cde in PROD_ORDER_TXT then select PROD_ORDER.cntry_cde (orders 100, 101, 103)
    2) If they are different, pick the country code from PROD_ORDER_TXT (order 102, AU <> NZ)
    3) If they are different and PROD_ORDER_TXT.cntry_cde is NULL, I cannot use it as cntry_cde in my report (order 104). It happenend just because of the bad data at source.
    I cannot avoid it. Then simply use the cntry_cde from PROD_ORDER
    Output expected
    100     US     A1     5
    101     US     A2     10
    102     NZ     A3     4 -- AU changed to NZ
    103     AU     A4     9
    104     IN     A5     3 -- IN retained as PROD_ORDER_TXT.cntry_cde is null
    sample table creation and insert statements are below
    create table prod_order
    (order_num number,
    cntry_cde CHAR(2),
    prod_id VARCHAR2(6),
    qty number)
    create table prod_order_txt
    (order_num number,
    cntry_cde CHAR(2),
    prod_id VARCHAR2(6))
    insert into prod_order values (100, 'US', 'A1',5);
    insert into prod_order values (101, 'US', 'A2',1);
    insert into prod_order values (102, 'AU', 'A3',4);
    insert into prod_order values (103, 'AU', 'A4',9);
    insert into prod_order values (104, 'IN', 'A5',3);
    insert into prod_order_txt values (100,'US','A1');
    insert into prod_order_txt values (101,'US','A2');
    insert into prod_order_txt values (102,'NZ','A3');
    insert into prod_order_txt values (103,'AU','A4');
    insert into prod_order_txt values (104,NULL,'A5');
    commit;
    Thanks for your help in advance
    Edited by: sarvan on Mar 28, 2012 1:39 PM

    Hello
    Thank you for posting all of the ddl and test data along with your expected output - very helpful!. One small point would be to remember to type {noformat}{noformat} before and after any section of code or data in your post so that formatting is retained.  Anyway, this should be a simple join and a combination of CASE and NVL...Select
    po.order_num,
    CASE
    WHEN po.cntry_cde != NVL(pot.cntry_cde,po.cntry_cde)
    THEN
    pot.cntry_cde
    ELSE
    po.cntry_cde
    END cntry_code,
    po.prod_id,
    po.qty
    FROM
    prod_order po
    JOIN
    prod_order_txt pot
    ON
    ( po.order_num = pot.order_num
    ORDER_NUM CN PROD_I QTY
    100 US A1 5
    101 US A2 1
    102 NZ A3 4
    103 AU A4 9
    104 IN A5 3
    5 rows selected.
    HTH
    David
    Edited by: Bravid on Mar 28, 2012 8:32 AM
    corrected !=                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

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

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

  • 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

  • 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

  • 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

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

  • SQL CASE Expression -need query.

    Hi All , i have query like this
    ----------------SELECT *
    FROM table A
    WHERE 1=1 and CASE WHEN :T=1 THEN (EXISTS
    (SELECT 'x'
    FROM
    (SELECT regexp_substr(str, '[^ ]+', 1, level) str
    FROM
    (SELECT 'SYS TAPE' str FROM dual
    ) t
    CONNECT BY instr(str, ' ', 1, level - 1) > 0
    ) x
    WHERE x.str not in('SYS','APPS')
    AND A.STR LIKE '%'
    || x.str
    || '%'
    )) ELSE A.STR END and a.sr=100;
    Getting errorORA-00905: missing keyword..Please help

    Well, I get other errors:
    SQL> SELECT *
      2  FROM table A
      3  WHERE 1=1 and CASE WHEN :T=1 THEN (EXISTS
      4  (SELECT 'x'
      5  FROM
      6  (SELECT regexp_substr(str, '[^ ]+', 1, level) str
      7  FROM
      8  (SELECT 'SYS TAPE' str FROM dual
      9  ) t
    10  CONNECT BY instr(str, ' ', 1, level - 1) > 0
    11  ) x
    12  WHERE x.str not in('SYS','APPS')
    13  AND A.STR LIKE '%'
    14  || x.str
    15  || '%'
    16  )) ELSE A.STR END and a.sr=100;
    SP2-0552: Bind variable "T" not declared.
    SQL> var T number
    SQL> SELECT *
      2  FROM table A
      3  WHERE 1=1 and CASE WHEN :T=1 THEN (EXISTS
      4  (SELECT 'x'
      5  FROM
      6  (SELECT regexp_substr(str, '[^ ]+', 1, level) str
      7  FROM
      8  (SELECT 'SYS TAPE' str FROM dual
      9  ) t
    10  CONNECT BY instr(str, ' ', 1, level - 1) > 0
    11  ) x
    12  WHERE x.str not in('SYS','APPS')
    13  AND A.STR LIKE '%'
    14  || x.str
    15  || '%'
    16  )) ELSE A.STR END and a.sr=100;
    FROM table A
    ERROR at line 2:
    ORA-00906: missing left parenthesis
    SQL> SELECT *
      2  FROM tableA
      3  WHERE 1=1 and CASE WHEN :T=1 THEN (EXISTS
      4  (SELECT 'x'
      5  FROM
      6  (SELECT regexp_substr(str, '[^ ]+', 1, level) str
      7  FROM
      8  (SELECT 'SYS TAPE' str FROM dual
      9  ) t
    10  CONNECT BY instr(str, ' ', 1, level - 1) > 0
    11  ) x
    12  WHERE x.str not in('SYS','APPS')
    13  AND A.STR LIKE '%'
    14  || x.str
    15  || '%'
    16  )) ELSE A.STR END and a.sr=100;
    WHERE 1=1 and CASE WHEN :T=1 THEN (EXISTS
    ERROR at line 3:
    ORA-00936: missing expressionFrom what I can make of it, looking at the concatenation of x.str in the query, you'll need dynamic SQL.
    Posting a small, working testcase that illustrates your requirement would really help.

Maybe you are looking for

  • HTML To MS Word Doc  Converion in Java

    Hey Guys , I need to know whether there is any component available in Java can convert my html document into MS word Thanking in advance

  • XPath - How to get only second matching node?

    Hello, withs this XPath expression: //td[contains(@name, 'FirstColumn')]on this XML: <html>      <table>           <tr>                <td name="MyFirstColumnInRow">A11 - skip me!</td>                <td name="MySecondColumnInRow">A12</td>           

  • Decision between call transaction and session method:BDC

    Hi, Kindly guide how to take decision between call transaction and session method? Thanks, Sanjay

  • Photoshop Elements 8 crashes when saving/opening file

    Hello, Since a day or two my PSE 8 crashes when i want to save or open a file. It just closes without a crash reporter. Is there anyone who can help me with this? Regards, Djmaster329

  • Migrate from Boot Camp to Parallels

    I've followed the threads about using the Boot Camp partition as a VM in Parallels, but I want to know if there is an advantage to keeping the Boot Camp partition if I doubt I'll ever need to re-boot into Boot Camp. I'm thinking I want to migrate my