none
Referencing a case stement in another case statement

    Question

  • I have one case statment(potentialretiree) see below.  Is it possible to reference my case statement name below in another case statment like this
    Case when potentialretiree = 1 then ' My text here'
          when potentialretiree =2 then ' my other text'
    else 'No'
    End 'Columnname1'

     

     

     

     

     

     

    Case WHEN (datediff(d,emp.brthdate,getdate())/365) > '55' and (datediff(d,emp.STRTDATE,getdate())/365) >'15' then '1'

     

    when (datediff(d,emp.brthdate,getdate())/365) > '50' and (datediff(d,emp.strtdate,getdate())/365) >'12' then '2'

     

    else 'No'

     

    End 'potentialretiree'
    Friday, May 13, 2011 2:36 PM

Answers

All replies

  • No, it's not possible., bacause it's simply an alias.
    Best regards
    Friday, May 13, 2011 2:48 PM
  • You can nest CASE expressions.

    Related article: http://www.sqlusa.com/bestpractices/training/scripts/casefunction/

    You can also make the SELECT with the CASE into a CTE, then you can reference it as virtual table applying a second CASE.

    Related article: http://www.sqlusa.com/bestpractices2005/cte/

     

     


    Kalman Toth, SQL Server & BI Training; SQL 2008 GRAND SLAM
    Friday, May 13, 2011 2:51 PM
  • For complex cases like this my favorite solution is in using CROSS APPLY. Please take a moment to take a look at the examples here

    Parsing the FullName field to individual components


    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog
    Friday, May 13, 2011 2:55 PM
  • Please post real DDL. Learn to use ISO-11179 rules for the data element names, avoid needless dialect and use ISO-8601 temporal formats, codes and so forth. people cannot read your mind, so post your code and clear specs if you really want help. 

    >> I have one CASE statement (potential_retiree) see below. <<

    WRONG! SQL has a CASE expression and not a CASE statement. Also, using single quotes for data element names is dialect; ANSI/ISO uses double quotes. Stop using the old Sybase/UNIX getdate(). I have the feeling that the table “Emp” should have been “Personnel”; non_RDBMS programmers do not think of the abstract set “Personnel” AND not a sequential file of employees.

    >>  Is it possible to reference my CASE statement [sic] name below in another CASE statement [sic] like this <<

    Short answer: NO! 

    Please, please, please read any book on SQL. It is a declarative language. All of the expressions in the SELECT come into existence all at once. It is not like languages that have statements that execute from left to right.

    First, let's clean up the expressions. Did you know we have a DATE data type? Do you know about the BETWEEN predicate? Oh, old procedural languages do not have such shorthands. You are writing your old language, but you are using SQL to do it. Here is an untested quick clean up.
     
    CASE WHEN DATEDIFF(YEAR, birth_date, CAST (CURRENT_TIMESTAMP AS DATE))
         BETWEEN 15 AND 55 THEN 'age_range_1'
         WHEN DATEDIFF(YEAR, birth_date, CAST (CURRENT_TIMESTAMP AS DATE))
         BETWEEN 12 AND 50 THEN 'age_range_2'
         ELSE 'No' END AS silly_overlapping_age_ranges,

    Here is how a SELECT works in SQL ... at least in theory.  Real products will optimize things, but the code has to produce the same results.

     a) Effectively materialize the CTEs in the optional WITH clause. CTE's come into existence in the order they are declared so only backward references are alllowed. A CTE can be recursive. Think of them as VIEWs that exist only in the scope of the query. In practice, if they are used once then they are implemented as an in-line macro.

     b) Start in the FROM clause and build a working table from all of the joins, unions, intersections, and whatever other table constructors are there.  The <table expression> AS <correlation name> option allows you give a name to this working table which you then have to use for the rest of the containing query.  Ther are UNIONB, INTERSECT and EXCEPT set construtors, LATERAL tables, table-valued funcitosn and all kinds of things happening in here.

     c) Go to the WHERE clause and remove rows that do not pass criteria; that is, that do not test to TRUE (i.e. reject UNKNOWN and FALSE).  The WHERE clause is applied to the working set in the FROM clause. 

     d) Go to the optional GROUP BY clause, partiton the original table into groups and reduce each grouping to a *single* row, replacing the original working table with the new grouped table. The rows of a grouped table must be only group characteristics: (1) a grouping column (2) a statistic about the group (i.e. aggregate functions) (3) a function or constant(4) an expression made up of only those three items.  The original table no longer exists and you cannot reference anything in it (this was an error in early Sybase products). 

     e) Go to the optional HAVING clause and apply it against the grouped working table; if there was no GROUP BY clause, treat the entire table as one group.

     f) Go to the SELECT clause and construct the expressions in the list. This means that the scalar subqueries, function calls and expressions in the SELECT are done after all the other clauses are done.  The AS operator can also give names to expressions in the SELECT list.  These new names come into existence all at once, but after the WHERE clause, GROUP BY clause and HAVING clause have been executed; you cannot use them in the SELECT list or the WHERE clause for that reason.

    If there is a SELECT DISTINCT, then redundant duplicate rows are removed.  For purposes of defining a duplicate row, NULLs are treated as matching (just like in the GROUP BY). 

     g) Nested query expressions follow the usual scoping rules you would expect from a block structured language like C, Pascal, Algol, etc.  Namely, the innermost queries can reference columns and tables in the queries in which they are contained. 

     h) The ORDER BY clause is part of a cursor, not a query. The result set is passed to the cursor, which can only see the names in the SELECT clause list, and the sorting is done there.  The ORDER BY clause cannot have expression in it, or references to other columns because the result set has been converted into a sequential file structure and that is what is being sorted. 

    As you can see, things happen "all at once" in SQL, not "from left to right" as they would in a sequential file/procedural language model. In those languages, these two statements produce different results:
      READ (a, b, c) FROM File_X;
      READ (c, a, b) FROM File_X;

    while these two statements return the same data:

    SELECT a, b, c FROM Table_X;
    SELECT c, a, b FROM Table_X;

    Think about what a confused mess this statement is in the SQL model.

    SELECT f(c2) AS c1, f(c1) AS c2 FROM Foobar;

    That is why such nonsense is illegal syntax.


     


    --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
    Friday, May 13, 2011 4:39 PM
  • WRONG! SQL has a CASE expression and not a CASE statement. Also, using single quotes for data element names is dialect; ANSI/ISO uses double quotes.

    CELKO,

    Do you think it would be worthwhile to get a copy of SQL Server 2008 Developer Edition for $49 and test your ideas before you post?  This is an MS SS T-SQL forum. Occasionally there are ANSI options like CURRENT_TIMESTAMP (getdate()), but most of the time there are no ANSI options.

    Look what happens with following your double quote idea:

     

    DECLARE @City varchar(32) = 'New York City' -- T-SQL syntax
    DECLARE @City1 varchar(32) = "New York City" -- ANSI SQL syntax
    /*
    Msg 207, Level 16, State 1, Line 2
    Invalid column name 'New York City'.
    */
    
    

     


    Kalman Toth, SQL Server & BI Training; SQL 2008 GRAND SLAM
    Friday, May 13, 2011 4:52 PM