简体   繁体   中英

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!

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.

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