case statement in SQL, how to return multiple variables?

后端 未结 9 2186
甜味超标
甜味超标 2020-12-05 13:40

I would like to return multiple values in my case statement, such as :

SELECT
  CASE
    WHEN  THEN 
    WHEN          


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 14:16

    The basic way, unfortunately, is to repeat yourself.

    SELECT
      CASE WHEN  THEN  WHEN  THEN  ELSE  END,
      CASE WHEN  THEN  WHEN  THEN  ELSE  END
    FROM 
      

    Fortunately, most RDBMS are clever enough to NOT have to evaluate the conditions multiple times. It's just redundant typing.


    In MS SQL Server (2005+) you could possible use CROSS APPLY as an alternative to this. Though I have no idea how performant it is...

    SELECT
      *
    FROM
      
    CROSS APPLY ( SELECT a1, b1 WHERE UNION ALL SELECT a2, b2 WHERE UNION ALL SELECT a3, b3 WHERE ) AS case_proxy

    The noticable downside here is that there is no ELSE equivalent and as all the conditions could all return values, they need to be framed such that only one can ever be true at a time.


    EDIT

    If Yuck's answer is changed to a UNION rather than JOIN approach, it becomes very similar to this. The main difference, however, being that this only scans the input data set once, rather than once per condition (100 times in your case).


    EDIT

    I've also noticed that you may mean that the values returned by the CASE statements are fixed. All records that match the same condition get the exact sames values in value1 and value2. This could be formed like this...

    WITH
      checked_data AS
    (
      SELECT
        CASE WHEN  THEN 1
             WHEN  THEN 2
             WHEN  THEN 3
             ...
             ELSE                   100
        END AS condition_id,
        *
      FROM
        
    ) , results (condition_id, value1, value2) AS ( SELECT 1, a1, b1 UNION ALL SELECT 2, a2, b2 UNION ALL SELECT 3, a3, b3 UNION ALL ... SELECT 100, a100, b100 ) SELECT * FROM checked_data INNER JOIN results ON results.condition_id = checked_data.condition_id

    提交回复
    热议问题