简体   繁体   中英

How to assign a value to a null query

I've a problem with a query in Oracle. I want to assign the value -1 if my query returns null and the ID value if in the table there is at least a value. This is my query

SELECT IAM_EXP_RESULT_ID
FROM (SELECT * FROM IAM_EXP_RESULT ORDER BY START_DATE  ASC)
WHERE RESULT = 0 AND ROWNUM = 1

The query above returns no rows because the table is empty. I want to create a variable to assign the value -1 in this case, or the IAM_EXP_RESULT_ID value in the case that at least a value exists.

You can use the COUNT analytic function and COALESCE :

SELECT COALESCE(
         IAM_EXP_RESULT_ID,
         CASE WHEN ct > 0 THEN -1 ELSE NULL END
       ) AS IAM_EXP_RESULT_ID
FROM   (
  SELECT IAM_EXP_RESULT_ID,
         RESULT,
         START_DATE,
         COUNT( your_value_column ) OVER () AS ct
  FROM   IAM_EXP_RESULT r
  UNION ALL
  SELECT -1, 0, NULL, 0 FROM DUAL
  ORDER  BY START_DATE ASC NULLS LAST
)
WHERE  RESULT = 0
AND    ROWNUM = 1

I use aggregation for this purpose:

SELECT COALESCE(MAX(IAM_EXP_RESULT_ID), -1)
FROM (SELECT *
      FROM IAM_EXP_RESULT
      ORDER BY START_DATE  ASC
     )
WHERE RESULT = 0 AND ROWNUM = 1;

An aggregation query always returns one row, with NULL if no rows match The COALESCE() replaces the value with what you want.

Note: You might want the RESULT = 0 in the subquery.

This general example in addition to others will return value if table has no rows and you cannot use count(*) or other aggregate function:

SELECT data_length FROM all_tab_cols
  WHERE owner = 'YOU'
   AND table_name = 'EMP'
   AND column_name = 'ENAMES'
UNION ALL
 SELECT -1 FROM dual
  WHERE NOT EXISTS
 (
  SELECT data_length FROM all_tab_cols
   WHERE owner = 'YOU'
     AND table_name = 'EMP'
     AND column_name = 'ENAMES'
  )
/

The result of above query is -1. The top portion may or may not return rows. If top portion returns rows then you get whatever it returns. If not then you get -1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM