If using a function in a case, does it run on each condition and result or is cached? In this example:
select case when someFunction() is null or someFunction() = 0 then 999 else someFunction() end

someFunction() runs three times or just one?
It runs every time you call it, in your case three times.
So rewrite the function that makes the case superfluous.