[英]How to assign a value to a null query
I've a problem with a query in Oracle. 我在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. 如果我的查询返回null,并且表中至少有一个值,则我想分配值-1。 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. 在这种情况下,我想创建一个变量来分配值-1,或者在至少存在一个值的情况下,创建IAM_EXP_RESULT_ID值。
You can use the COUNT
analytic function and COALESCE
: 您可以使用COUNT
分析函数和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. 聚合查询总是返回一行, NULL
,如果没有相匹配的行的COALESCE()
替换为你想要的值。
Note: You might want the RESULT = 0
in the subquery. 注意:您可能希望子查询中的RESULT = 0
。
This general example in addition to others will return value if table has no rows and you cannot use count(*) or other aggregate function: 如果表没有行并且您不能使用count(*)或其他聚合函数,那么除其他示例外,该常规示例还将返回值:
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. 以上查询结果为-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. 如果不是,则得到-1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.