I have this query (pseudo code)
SELECT
a = 1,
b = 2,
c = CASE
WHEN ISNULL(
(SELECT MONTH(GETDATE()) <---long query
), 0) = 0 THEN 'found'
ELSE
SELECT MONTH(GETDATE()) <--- repeated long query
END
The problem is that the SELECT MONTH(GETDATE()) which in reality is very long query.
Is there any workaround for this “long expression” not to appear twice in the query ?
p.s.
I have a solution of calculating SELECT MONTH(GETDATE()) into an outside variable… but I’m trying to figure out if there’s an inline solution.
The particular pattern of usage of a subquery in your example could be re-written like this:
As Mikael Eriksson has correctly pointed out in his comment, you may need to use
ISNULLinstead ofCOALESCEhere, because one of the arguments contains a subquery andISNULLmay (or, in fact, will) be more efficient in this case, as you can see elaborated in this answer.so here is the fixed ver :
Note, though, that if you end up switching to
ISNULL, you should pay attention to the length of the second string ('found') if you ever decide to change it too. The thing is,ISNULLwill (attempt to) cast the second argument to the exact type of the first argument, including the maximum length of the string specified (10in this case). If your second argument becomes something like'NULL or zero is found'instead of just'found',ISNULLwill not return the entire string but only the first 10 characters instead ('NULL or ze'). So you’ll need to remember to change the type of the first argument as well (tovarchar(20), for instance).