Lock
Lock

Reputation: 5522

oracle function similar to decode, but simpler

In oracle, I can use the function decode in an "if, then else" way.

So for example:

DECODE(XXXX,'TEST',NULL,XXXX).

So the above is saying "if XXXX = 'TEST', then NULL, else XXXX".

Now that gets my desired result, but is there a shorter way (a nativefunction perhaps) that can write it such as this:

DECODE(XXXX,'TEST',NULL)

So basically, If the first argument = 'TEST', then output NULL, else output the first argument.

A little like NVL where as NVL will return the first argument if its not null.

I am just curious as some of my statements are very long and it seems quite a waste to have the required output twice in a function.

I know I can make a custom function, but just curious if there is already one.

Hope that makes sense!

Upvotes: 1

Views: 532

Answers (1)

Justin Cave
Justin Cave

Reputation: 231881

In this particular case, you can use NULLIF()

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1 id, 'foo' str from dual union all
  3    select 2, 'TEST' from dual
  4  )
  5  select id,
  6         nullif( str, 'TEST' )
  7*   from x
SQL> /

        ID NULL
---------- ----
         1 foo
         2

Personally, though, I would tend to prefer a more verbose CASE or DECODE rather than using some of the more esoteric built-in functions simply because it's a lot more likely that whoever has to maintain the code in the future will have an easier time following what the code is supposed to be doing.

Upvotes: 4

Related Questions