简体   繁体   中英

Stored procedure using NVL() on input parameter - why?

Recently, I have come to analyze a procedure in which they have used below scenario. I want to know what is the usefulness of this ?

A procedure (cwrkid, date)

select statement

  WHERE CWRK.cwrkid = NVL(in_cwrk_id,CWRK.cwrkid)

and in_cwrk_id is passed null . SO obviously, CWRK.cwrkid = CWRK.cwrkid will always match... What the point in using variables and passing null , and ultimately satisfying a truth condition.

Am I mising something or am I thinking a lot.. :P

This is useful if you want to make the procedure reusable in future development. For now the only usecase is to select all records, but if you ever need to get only one record with a given ID you can also use this procedure.

The point is that the caller can decide whether a filter on cwrkid should be applied. One call to that function may pass NULL for that parameter, to not apply any filter. Another call to that function may pass some value for that parameter, if that caller does want to apply a filter.

I say that no filter gets applied, but I am assuming that the column is not nullable. If the column is nullable, then nulls will be filtered out, regardless of what gets passed in as the parameter value.

Normally, code like this is used to have a default behaviour in case the parameter is NULL . In this case, the WHERE-condition normally restricts to records with the given cwrkid . However, if cwrkid is null, there is no restriction.

Without the NVL , the WHERE-condition would not match at all.

Why this was done in this case is impossible to know without knowing more about the procedure and its purpose.

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