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

前端 未结 6 1672
余生分开走
余生分开走 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:54

    Here is my simple solution using LEFT OUTER JOIN:

    CREATE TABLE data_table(data_name VARCHAR2(20), data_type NUMBER(2));
    
    INSERT INTO data_table(data_name, data_type) VALUES('fifty-one', 51);
    
    SELECT coalesce(data_name, 'unknown')
      FROM dual
      LEFT OUTER JOIN (SELECT data_name FROM data_table WHERE data_type = 53) o
        ON 1 = 1;
    
    SELECT coalesce(data_name, 'unknown')
      FROM dual
      LEFT OUTER JOIN (SELECT data_name FROM data_table WHERE data_type = 51) o
        ON 1 = 1;
    

提交回复
热议问题