简体   繁体   中英

oracle if 0, like if null (nvl)

oracle has a nice built in function for doing if null, however I want to do if = 0; is there a simple way to do this?

nvl(instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' '), length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))))

This is going as a parameter to a substr function.

If instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' ') is != 0 then I want that value, otherwise I want the value of length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))

is there an easy way to do this?

You can use NVL(NULLIF(A,'0'), B)

You could technically do this with less typing as:

nvl(
    nullif(instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' '),0),
    length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))
)

However, I would typically side with Conrad and advise you to use CASE so it is easier to tell what the intent of the code is for future maintenance.

I found both answers hard to read because of the extra verbiage from the original post. Summarizing Conrad and Craig's answers:

To replicate nvl(A,B) but for 0 instead of null, you can do:

WHEN A != 0 THEN
  A
ELSE
  B
END

or Craig's more compact (but harder for others to read):

NVL(NULLIF(A,0),B)

I think that the following would also work:

DECODE(A,0,B,A)

I think you'll need to use CASE

eg

WHEN instr(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5),' ') != 0 THEN
  length(substr(ovrflo_adrs_info,instr(ovrflo_adrs_info,'bldg')+5))
ELSE
   Some Default
END as foo

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