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.

Similar Messages

  • 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

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

  • Using null in CASE statements

    Hi,
    I have query with a case statement as follows:
    SELECT * FROM table
    WHERE
    CASE WHEN :variable like 'A' THEN column END is null
    WHEN :variable like 'B' THEN column END is not null;
    This works fine when returning "column is null" but not when "column is not null".
    Can I use a CASE statement like this?
    Thanks
    Lucy

    My data is too complicated to show, but depending on the value of the bind variable in the statement I want to return all the rows in a query where the data in a particular column is either null or not null.For example, looking at the EMP table, if my bind variable is whether I want to show the top manager or not, if set to 'Yes' I would like to return all rows of the EMP table where mgr is null (i.e. the one row where ename is 'KING'), if it were set to 'No' I would like to return all the rows where mgr is not null (i.e. all the other rows). The difference with my query is that the column contains strings, not numerics.
    I've used a CASE statement before where I equate the column to a particular value and that works fine, but I'm not sure how they deal with nulls. I've also tried DECODE and didn't get anywhere with that.
    Thanks
    Lucy

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

  • Issue with TableAdapter Configuration Wizard and CASE statements

    I am having an issue with using any CASE statements in the select clause for the Table Adapter Configuration Wizard (TCW).  I can take any query without a CASE and it will run fine, but inserting any CASE statement in the Select such as:
    SELECT
    (CASE WHEN :ras_sort = 'D' THEN TO_CHAR(a.TRANS_DATE,'YYYYMMDD')
      WHEN :ras_sort = 'C' THEN  c.CLAIMDEP_NAME
      WHEN :ras_sort = 'A' THEN  TO_CHAR(a.ACCOUNT_NUMBER)
      END) sort1
    FROM xxxx
    causes the TCW to error with "error in list of function arguments, 'THEN' not recognized" and several other errors.  I have tried with and without parameters in the CASE and have tried both forms of the CASE statement.  I have tried multiple queries, all that run with no problem outside of TCW and ODP, but this seems to be a real issue
    Is this a known problem and are there any workarounds that will allow use of the TCW?
    Thanks,
    Dave

    Hi Ashish,
    perhaps you launch the Web service wizard from the wrong location (i.e. not selecting the SEI you want to use). Did you strictly follow the steps described in the <a href="http://help.sap.com/saphelp_nwce10/helpdata/en/44/f36fa8fd1d41aae10000000a114a6b/frameset.htm">documentation</a> for creating the web service?

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

  • Creating view containing case statements received error ORA-22992

    We have a create view referencing table through dblink. The select statement in the create view has case statements, when running the Select statement alone, results are return. However, when executing the create view, it returns:
    SQL Error: ORA-22992: cannot use LOB locators selected from remote tables
    22992. 00000 - "cannot use LOB locators selected from remote tables"
    *Cause:    A remote LOB column cannot be referenced.
    *Action:   Remove references to LOBs in remote tables.
    One of the source table has LOB column but not in the select statement. The strange thing is when removing the case statement from the select, create view works fine. Can anybody tell me what caused the error and how to fix it?
    Create View Snippet:
    CREATE OR REPLACE VIEW "ABC"."XYZ" (....
    AS SELECT
    CASE
    WHEN A.OUTAGE =1
    THEN 'Y'
    ELSE 'N'
    END AS OUTAGE,
    FROM
    TABLEA@XXXX A
    LEFT JOIN TABLEB@XXXX B
    ON
    A.LOC =B.LO
    AND A.SITE =B.SITE
    WHERE
    A.CLASS ='CUSTOMER'
    AND A.PLUSSISGIS =1;

    What is your 4 digit Oracle version?
    Try rewriting the query to not use ANSI SQL92 joins. I found a link where this solved a problem similar to yours.
    DBLink problem ORA-22992
    >
    But, look at this curious thing: I re-write the query as follows:
    SELECT A.ID, A.ID_REF, A.EVENDATE, B.DESCRIPTION
    FROM A@ORCL A, B@ORCL B
    WHERE A.ID_REF = B.ID_REF;
    and it works fine... It seems like Oracle don't like the ANSI SQL92...
    >
    Several similar links by googling: 'SQL Error: ORA-22992'
    http://www.dbuggr.com/smallwei/solution-error-ora-22992-lob-locators-selected-remote-tabl/
    >
    Fixing ORA-22992 “cannot use LOB locators selected from remote tables” error
    You have migrated your Oracle 9i database to 10g and a distributed statement which worked fine in 9i now is getting error ORA-22992 “cannot use LOB locators selected from remote tables”. Even though the related remote table(s) does not contain any LOB column datatype.
    FIX:
    There is a bug on 9i,10g, and 11g that is related to this error. It is being fixed in 11.2. It can also be backported for previous 9i, 10g and 11g releases under the latest patchsets.
    You may also do a workaround as follow:
    Modify the affected SQL by adding the TO_CHAR function. For example:
    -- Original SQL:
    SELECT NVL2('a', 'b','c' ) FROM dual@remote_db;
    -- Modified SQL:
    SELECT TO_CHAR(NVL2('a','b','c')) FROM dual@remote_db;
    >
    See if that helps.

  • Help with multiple case statements

    Hello,
    I am new to BO.  I am on XI 3.0.  SQL 2005.  In Designer, I am trying to create a measure in a financial universe that would end up being multiple case statements within one select.  This is what I tried to do, but it doesn't work with the two case statements.  Can I use an ELSE leading into the second CASE WHEN somehow?  How can I accomplish this?  Sorry for my ignorance!
    CASE WHEN dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month = 12 THEN dbo.ClientBudgetMonth.Stage1Sales END
    CASE WHEN  dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month = 11 THEN dbo.ClientBudgetMonth.Stage1Sales END
    Any Suggestions?
    Thanks,
    Holly

    Holly,
    I don't know enough about your data or requirement to provide a solution, however, the construct that you post will not work because it causes you to build an object with multiple case statements when only one case statement per object is permitted.  From what I see in your code I would be inclined to combine the two statements into one as such:
    CASE WHEN dbo.ClientBudgetYear.DateStage1Approved > 01/01/1900 AND dbo.ClientBudgetMonth.Month in (11,12) THEN dbo.ClientBudgetMonth.Stage1Sales else null END
    Thanks,
    John

  • Performance in a case statement

    Hi
    I have a query like this -
    SELECT
    MAX(CASE WHEN field1 = 'xyz' THEN field2 END) AS alias1,
    MAX(CASE WHEN field2 = 'abc' THEN field2 END) AS alias2
    FROM table1
    WHERE
    field1 = 'xyz' and
    field2 = 'abc' and
    some fixed condition
    Please note that the conditions in where clauses are same as corresponding case statements apart from one fixed condition.
    In the actual query there are ~15 such conditions and 15 case statements for each selected field.
    I have put the where clause to reduce the number of rows getting returned from the table.
    My question is - what happens in terms of performance if I remove the where clause here. In other words will above query perform better or same as this
    SELECT
    MAX(CASE WHEN field1 = 'xyz' THEN field2 END) AS alias1,
    MAX(CASE WHEN field2 = 'abc' THEN field2 END) AS alias2
    FROM table1
    WHERE
    some fixed condition
    Thanks
    Kumar

    It really depends on what you query is trying to accomplish. The two queries are not the same. Your first will select rows where both field1 = 'xyz' and field2 = 'abc', while the second would also return rows where, for example, field1 = 'xyz' and field2 = 'def'. In which case, your alias2 would be null.
    John

  • Case statement with Subquery

    Case statement with Subquery
    select case when condition then
    i want to execute qr1
    else qr2
    How to implement this ?

    Hi,
    Welcoem to the forum!
    972471 wrote:
    Case statement with SubqueryHow does a sub-query, or a query, figure in this question?
    Be more specific. Post a complete script that you tried, and what output you expected from it. If you got an error, post the complete error message, including line numbers.
    See the forum FAQ {message:id=9360002}
    select case when condition then
    i want to execute qr1
    else qr2
    How to implement this ?Here's one way:
    BEGIN
        CASE
            WHEN  1 = 1
            THEN
                dbms_output.put_line ('Condition was TRUE');
            ELSE
                dbms_output.put_line ('Condition was FALSE or UNKNOWN');
        END CASE;
    END;
    /If the condition involves a query, then you may have to select the results into a variable first, and then use the variable in the CASE statement.

  • Nested Case Statement

    Hello,
    I need help implementing multiple Case Statements in a select statement. I can not get this to work in one statement.
    Select Statement
    select distinct
    allt.fk_jobcode_id as Job_Code,
    allt.fk_jobcode_descr as Classification,
    sum(allt.number_of_positions) as Number_Allotted,
    sum(number_of_positions) as Sum_Number_Allotted,
         dept.department_name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
      END),'/'||DIV.DIVISION_NAME||'',null) as Department_Division,
    allt.fund_type as Fund
    from tbl_allotment allt, tbl_department dept, tbl_division div
    where isdeleted <> 'Y'
    and ALLT.FK_DEPARTMENT_ID = dept.department_id
    and ALLT.FK_DIVISION_ID = div.division_id
    group by fk_jobcode_id, fk_jobcode_descr, fund_type, department_name, division_name
    HAVING (count(fk_jobcode_descr ) = 1)
    order by Classification asc, Department_Division asc1st CASE Statement combines the Department_Name and Division_Name values but does not display the Division_Name if the value is 'N/A'.
         dept.department_name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
      END),'/'||DIV.DIVISION_NAME||'',null) as Department_Division,value: Council Administrator's Office/Administration
    value: Council Administrator's Office/N/A will display as Council Administrator's Office
    I need to extend this now by using this CASE Statement, which displays the text 'Public Works' if the Department_Id = 00072.
         (CASE dept.department_id
         When '00072' then 'Public Works'
         Else dept.Department_Name
         End) as Department_Name, incorrect: Road Rehab Program/GLP Transportation Program Admin
    Should populate as: Public Works/GLP Transportation Program Admin
    select distinct
    allt.fk_jobcode_id as Job_Code,
    allt.fk_jobcode_descr as Classification,
    sum(allt.number_of_positions) as Number_Allotted,
    sum(number_of_positions) as Sum_Number_Allotted,
         dept.department_name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
      END),'/'||DIV.DIVISION_NAME||'',null) as Department_Division,
      (CASE dept.department_id
         When '00072' then 'Public Works'
        ELSE dept.Department_Name|| ''||nvl2((CASE WHEN div.division_name <> 'N/A'
        THEN div.division_name 
           END),'/'||DIV.DIVISION_NAME||'',null)
      END) as Department_Name1,
    allt.fund_type as Fund
    from tbl_allotment allt, tbl_department dept, tbl_division div
    where isdeleted <> 'Y'
    and ALLT.FK_DEPARTMENT_ID = dept.department_id
    and ALLT.FK_DIVISION_ID = div.division_id
    group by fk_jobcode_id, fk_jobcode_descr, fund_type, department_name, division_name, department_id
    HAVING (count(fk_jobcode_descr ) = 1)
    order by Classification asc, Department_Division ascbut once I modify the select statement I am only getting value 'Public Works' for Department_Division value. Does not populate the Division_Name data. Does anyone know how to combine these CASE Statements? Thanks for reading this Thread also.

    Hi,
    I think you want something like this:
    SELECT       ...
    ,       CASE
               WHEN  department_id = '00072'
               THEN  'Public Works'
               ELSE  dept.department_name
           END
           ||
           CASE
               WHEN  div.division_name != 'N/A'
               THEN  '/' || div.division_name
           END          AS department_name1
    ...Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using.

  • How can you change a drop down menu's selection in a case statement?

    Hi,
    I am trying to an array finding vi. This VI will take an existing xml file and after the user has selected his/her equipment, input, output, and frequency it will put all of those options into a string and search the xml file for that exact array name and display it on an output screen. The problem I am having is that my input and outputs selection needs to be a little different depending upon the equipment selected. I thought that I could use a case statement to change the input and output selectable options, but I have run into many snags with it. For one everytime I place a new Input and Output drop down menu in the case statement it wants to place a new one in the front panel (I only want one input and output not three I have two inputs and outputs hidden right now). I believe I am using the case statement wrong... Can anyone help change my input and output selectable options depending upon the equipment selected. Attached is my xml file, Array Find.vi (the original one), and Array Find_Test.vi (this is the one I am trying to modify).
    Thanks,
    dlovell
    Solved!
    Go to Solution.
    Attachments:
    Find Array.zip ‏126 KB

    Hi dlovell,
    There are 2 key things I'd recommend for the code - using property nodes to edit the strings in the combo boxes.  Something like the following snippet:
    Also, check your CPU in task manager when running the code.  It will eat a whole core of your machine (25% quad core, 50% dual, 100% single) - that is because you are running the while loop and polling the control as fast as Windows will allow you to.  Using Event Structures is a much more efficient way of working in this example.
    Check out the MOD attached 
    Regards,
    Peter D
    Attachments:
    MOD_Find Array.vi ‏28 KB

  • Using a scalar user defined function in a select case statement

    I have a simple select statement below and I want to have a case statement for some conditions based on the result of the udf returned value. I then want the returned value from that specific case statement to be returned where i have indicated 'DISPLAY
    ZIPCODE' below.
    SELECT
        CASE
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             WHEN (SELECT Top 1 ZipCode FROM ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,714) as r) IS NOT NULL THEN 'DISPLAY ZIPCODE'
             ELSE NULL
           END as Zipcode,
    FROM
    table1

    SELECT COALESCE(ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712),ufn_GetAddressByBusinessEntityIDandAddressTypeID(table1.BusinessEntityID,712)) AS Zipcode
      FROM table1
    Nope. This is two function calls. coalesce(a, b, c, ...) is just syntatic sugar for
       CASE WHEN a IS NOT NULL THEN a
            WHEN b IS NOT NULL THEN b
            WHEN c IS NOT NULL THEN c
       END
    But if you use isnull it's a different matter. (But isnull() permits two arguments.)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Case statement and Decode function both are not working in Select cursor.

    I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. On the other hand both the things work in just select statement.
    See the first column in select (PAR_FLAG), I need to have this evaluated along with other fields. Can you please suggest some thing to make this work. And also I would like to
    know the reason why decode is not working, I heard some where Case statement do not work with 8i.
    Author : Amit Juneja
    Date : 06/20/2011
    Description:
    Updates the Diamond MEMBER_MASTER table with the values from
    INC.MEM_NJ_HN_MEMBER_XREF table.
    declare
    rec_cnt number(12) := 0;
    commit_cnt number(4) := 0;
    cursor select_cur is
    Select DECODE(1,
    (Select 1
    from hsd_prov_contract R
    where R.seq_prov_id = PM.seq_prov_id
    and R.line_of_business = H.line_of_business
    and R.PCP_FLAG = 'Y'
    and R.participation_flag = 'P'
    and SYSDATE between R.EFFECTIVE_DATE AND
    NVL(R.TERM_DATE,
    TO_DATE('31-DEC-9999', 'DD-MON-YYYY'))),
    'Y',
    'N') PAR_FLAG,
    H.SEQ_ELIG_HIST,
    H.SEQ_MEMB_ID,
    H.SEQ_SUBS_ID,
    H.SUBSCRIBER_ID,
    H.PERSON_NUMBER,
    H.EFFECTIVE_DATE,
    H.TERM_DATE,
    H.TERM_REASON,
    H.RELATIONSHIP_CODE,
    H.SEQ_GROUP_ID,
    H.PLAN_CODE,
    H.LINE_OF_BUSINESS,
    H.RIDER_CODE_1,
    H.RIDER_CODE_2,
    H.RIDER_CODE_3,
    H.RIDER_CODE_4,
    H.RIDER_CODE_5,
    H.RIDER_CODE_6,
    H.RIDER_CODE_7,
    H.RIDER_CODE_8,
    H.MEDICARE_STATUS_FLG,
    H.OTHER_STATUS_FLAG,
    H.HIRE_DATE,
    H.ELIG_STATUS,
    H.PREM_OVERRIDE_STEP,
    H.PREM_OVERRIDE_AMT,
    H.PREM_OVERRIDE_CODE,
    H.SEQ_PROV_ID,
    H.IPA_ID,
    H.PANEL_ID,
    H.SEQ_PROV_2_ID,
    H.SECURITY_CODE,
    H.INSERT_DATETIME,
    H.INSERT_USER,
    H.INSERT_PROCESS,
    H.UPDATE_DATETIME,
    H.UPDATE_USER,
    H.UPDATE_PROCESS,
    H.USER_DEFINED_1,
    H.SALARY,
    H.PEC_END_DATE,
    H.REASON_CODE,
    H.PEC_WAIVED,
    H.BILL_EFFECTIVE_FROM_DATE,
    H.BILLED_THRU_DATE,
    H.PAID_THRU_DATE,
    H.SUBSC_DEPT,
    H.SUBSC_LOCATION,
    H.USE_EFT_FLG,
    H.BENEFIT_START_DATE,
    H.SEQ_ENROLLMENT_RULE,
    H.MCARE_RISK_ACCRETION_DATE,
    H.MCARE_RISK_DELETION_DATE,
    H.MCARE_RISK_REFUSED_DATE,
    H.COMMENTS,
    H.USER_DEFINED_2,
    H.USER_DEFINED_3,
    H.RATE_TYPE,
    H.PCPAA_OCCURRED,
    H.PRIVACY_ON,
    H.PCP_CHANGE_REASON,
    H.SITE_CODE,
    H.SEQ_SITE_ADDRESS_ID,
    PM.seq_prov_id rendered_prov
    from hsd_member_elig_history H,
    INC.PCP_REASSIGN_RPRT_DATA P,
    hsd_prov_master PM
    where P.subscriber_id = H.subscriber_id
    and P.rendered_pcp = PM.provider_ID
    and H.elig_status = 'Y'
    and (H.term_date is NULL or H.term_date >= last_day(sysdate))
    order by H.Seq_memb_id;
    begin
    for C in select_cur loop
    rec_cnt := rec_cnt + 1;
    update hsd_member_elig_history
    set term_date = TRUNC(SYSDATE - 1),
    term_reason = 'PCPTR',
    update_datetime = SYSDATE,
    update_user = USER,
    update_process = 'TD33615'
    where seq_elig_hist = C.seq_elig_hist
    and seq_memb_id = C.seq_memb_id;
    INSERT INTO HSD_MEMBER_ELIG_HISTORY
    (SEQ_ELIG_HIST,
    SEQ_MEMB_ID,
    SEQ_SUBS_ID,
    SUBSCRIBER_ID,
    PERSON_NUMBER,
    EFFECTIVE_DATE,
    TERM_DATE,
    TERM_REASON,
    RELATIONSHIP_CODE,
    SEQ_GROUP_ID,
    PLAN_CODE,
    LINE_OF_BUSINESS,
    RIDER_CODE_1,
    RIDER_CODE_2,
    RIDER_CODE_3,
    RIDER_CODE_4,
    RIDER_CODE_5,
    RIDER_CODE_6,
    RIDER_CODE_7,
    RIDER_CODE_8,
    MEDICARE_STATUS_FLG,
    OTHER_STATUS_FLAG,
    HIRE_DATE,
    ELIG_STATUS,
    PREM_OVERRIDE_STEP,
    PREM_OVERRIDE_AMT,
    PREM_OVERRIDE_CODE,
    SEQ_PROV_ID,
    IPA_ID,
    PANEL_ID,
    SEQ_PROV_2_ID,
    SECURITY_CODE,
    INSERT_DATETIME,
    INSERT_USER,
    INSERT_PROCESS,
    UPDATE_DATETIME,
    UPDATE_USER,
    UPDATE_PROCESS,
    USER_DEFINED_1,
    SALARY,
    PEC_END_DATE,
    REASON_CODE,
    PEC_WAIVED,
    BILL_EFFECTIVE_FROM_DATE,
    BILLED_THRU_DATE,
    PAID_THRU_DATE,
    SUBSC_DEPT,
    SUBSC_LOCATION,
    USE_EFT_FLG,
    BENEFIT_START_DATE,
    SEQ_ENROLLMENT_RULE,
    MCARE_RISK_ACCRETION_DATE,
    MCARE_RISK_DELETION_DATE,
    MCARE_RISK_REFUSED_DATE,
    COMMENTS,
    USER_DEFINED_2,
    USER_DEFINED_3,
    RATE_TYPE,
    PCPAA_OCCURRED,
    PRIVACY_ON,
    PCP_CHANGE_REASON,
    SITE_CODE,
    SEQ_SITE_ADDRESS_ID)
    values
    (hsd_seq_elig_hist.nextval,
    C.SEQ_MEMB_ID,
    C.SEQ_SUBS_ID,
    C.SUBSCRIBER_ID,
    C.PERSON_NUMBER,
    trunc(SYSDATE),
    C.TERM_DATE,
    C.TERM_REASON,
    C.RELATIONSHIP_CODE,
    C.SEQ_GROUP_ID,
    C.PLAN_CODE,
    C.LINE_OF_BUSINESS,
    C.RIDER_CODE_1,
    C.RIDER_CODE_2,
    C.RIDER_CODE_3,
    C.RIDER_CODE_4,
    C.RIDER_CODE_5,
    C.RIDER_CODE_6,
    C.RIDER_CODE_7,
    C.RIDER_CODE_8,
    C.MEDICARE_STATUS_FLG,
    C.OTHER_STATUS_FLAG,
    C.HIRE_DATE,
    C.ELIG_STATUS,
    C.PREM_OVERRIDE_STEP,
    C.PREM_OVERRIDE_AMT,
    C.PREM_OVERRIDE_CODE,
    C.SEQ_PROV_ID,
    C.IPA_ID,
    C.PANEL_ID,
    C.SEQ_PROV_2_ID,
    C.SECURITY_CODE,
    SYSDATE,
    USER,
    'TD33615',
    SYSDATE,
    USER,
    'TD33615',
    C.USER_DEFINED_1,
    C.SALARY,
    C.PEC_END_DATE,
    C.REASON_CODE,
    C.PEC_WAIVED,
    C.BILL_EFFECTIVE_FROM_DATE,
    C.BILLED_THRU_DATE,
    C.PAID_THRU_DATE,
    C.SUBSC_DEPT,
    C.SUBSC_LOCATION,
    C.USE_EFT_FLG,
    C.BENEFIT_START_DATE,
    C.SEQ_ENROLLMENT_RULE,
    C.MCARE_RISK_ACCRETION_DATE,
    C.MCARE_RISK_DELETION_DATE,
    C.MCARE_RISK_REFUSED_DATE,
    C.COMMENTS,
    C.USER_DEFINED_2,
    C.USER_DEFINED_3,
    C.RATE_TYPE,
    C.PCPAA_OCCURRED,
    C.PRIVACY_ON,
    C.PCP_CHANGE_REASON,
    C.SITE_CODE,
    C.SEQ_SITE_ADDRESS_ID);
    commit_cnt := commit_cnt + 1;
    if (commit_cnt = 1000) then
    dbms_output.put_line('Committed updates for 1000 records.');
    commit;
    commit_cnt := 0;
    end if;
    end loop;
    commit;
    dbms_output.put_line('Total number of MEMBER_ELIG_HISTROY records inserted : ' ||
    rec_cnt);
    exception
    when others then
    raise_application_error(-20001,
    'An error was encountered - ' || sqlcode ||
    ' -error- ' || sqlerrm);
    end;

    user10305724 wrote:
    I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. Please define what you mean by not working even if your computer screen is near the internet we can't see it.
    You should also look at the FAQ about how to ask a question
    SQL and PL/SQL FAQ
    Particularly *9) Formatting with {noformat}{noformat} Tags* and posting your version.
    know the reason why decode is not working, I heard some where Case statement do not work with 8i.
    Does this mean you are using 8i? Then scalar sub queries - selects within the select list, are not supported, along with CASE in PL/SQL.
    Select DECODE(1,
    * (Select 1
    from hsd_prov_contract R
    where R.seq_prov_id = PM.seq_prov_id
    and R.line_of_business = H.line_of_business
    and R.PCP_FLAG = 'Y'
    and R.participation_flag = 'P'
    and SYSDATE between R.EFFECTIVE_DATE AND
    NVL(R.TERM_DATE,
    TO_DATE('31-DEC-9999', 'DD-MON-YYYY')))*,
    'Y',
    'N') PAR_FLAG,
    >
    exception
    when others then
    raise_application_error(-20001,
    'An error was encountered - ' || sqlcode ||
    ' -error- ' || sqlerrm);
    http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for