Oracle: Get a query to always return exactly one row, even when there's no data to be found

前端 未结 6 1665
余生分开走
余生分开走 2021-01-18 01:17

I have a query like this:

   select data_name
   into v_name
   from data_table
   where data_table.type = v_t_id

Normally, this query shou

6条回答
  •  时光说笑
    2021-01-18 01:47

    There's ways to make this simpler and cleaner, but this basically spells out the technique:

    SELECT data_name
    FROM data_table
    WHERE data_table.type = v_t_id
    
    UNION ALL
    
    SELECT NULL AS data_name
    FROM dual
    WHERE NOT EXISTS (
        SELECT data_name
        FROM data_table
        WHERE data_table.type = v_t_id
    )
    

    When the first part of the union is empty the second will contain a row, when the first part is not empty, the second will contain no rows.

    If the query is takes to much time, use this one:

    SELECT * FROM (  
        SELECT data_name
        FROM data_table
        WHERE data_table.type = v_t_id
    
        UNION ALL
    
        SELECT NULL AS data_name
        FROM dual
      ) WHERE data_name is not null or ROWNUM = 1
    

提交回复
热议问题