0

I am looking at a cursor with decode(1, 1, 1, NULL, 0) in the SELECT statement. The query returns records of employees that have worked for 5 years or more. I assume that the intention of the decode statement was to check if a record is returned or not (meaning that said employee has worked for five or more years).

This approach doesn't seem to work. It could be because I am simply putting in the wrong dummy data. Is my assumption correct(that this approach doesn't work)? If I am incorrect, how does this decode statement accomplish the goal of identifying if a record is returned?

CURSOR worked_more_then_five_years
IS
SELECT decode(1, 1, 1, NULL, 0)
FROM table
WHERE /*query conditions*/
4

4 回答 4

1

The decode statement is affecting the return values on the row or rows that are returned.

To guarantee that a row is returned, you are better off using an aggregation:

CURSOR worked_more_then_five_years
IS
SELECT (case when count(*) > 0 then 1 else 0 end)
FROM table
WHERE /*query conditions*/

The case statement is the SQL standard "equivalent" to decode(). The aggregation will always return one row. If there are no matches, the value is 0; if there are matches, then the first clause is met and the return value is 1.

于 2013-06-04T01:51:28.633 回答
1

To guarantee the return of a single row with an indication of whether the condition was met or not:

select count(*) row_found
from   table
where  ...
  and  rownum <= 1;

As long as there are no other (non-aggregating) columns then you will always get a single row returned.

If your predicates guarantee that only one row matches the condition then of course you can leave the rownum predicate off, and in fact can also return values as long as an aggregate is used:

select count(*) row_found,
       min(employee_id) employee_id,
       min(date_started) date_started
       ...
from   table
where  predicate_to_return_one_row.
于 2013-06-04T06:14:14.017 回答
0

CURSOR worked_more_then_five_years IS SELECT decode(1, 1, 1, NULL, 0) FROM table WHERE /query conditions/

The first parameter of Decode has to be Column Name. Ex) SELECT DECODE(WORK_YEAR, '5', WORK_YEAR, NULL) FROM TABLE

That statements means "If WORK_YEAR is '5', then it should be outputed '5', if WORK_YEAR is not '5', then all of output is 'null'."

于 2013-06-04T07:07:43.713 回答
-1

The decode statement works like an "if-then-else", so in case we don't provide any default case it returns null. It basically helps in manipulating data during retrieval.

In your statement what are you comparing?

于 2013-06-04T01:10:18.230 回答