The following (simplified and obfuscated) query appears to (in my
mind) return a varchar type from each possible return branch in the
nested case expression. I went to the trouble of casting the first
two possible return branches to varchar to ensure their congruence
with the last two possible return types as represented in the last
(most deeply nested) case statement which returns strings. However,
when run, it complains about trying to convert the string ‘foo’ to an
int. Everything worked fine until I added that bottommost, most
deeply nested, case statement that always returs strings (and indeed,
before I added that, there was no need for any conversion of dates
since dates were all that could ever be returned). QUESTION: Any
idea why sql server is trying to convert the ‘foo’ string (and
probably ‘bar …’ string if it could get that far) into an int? More
importantly, any ideas on a solution to solve the casting/conversion
issue? Thanks in advance.
select case
when t1.flubbitz - t1.dubbitz <= 0
then
case
when (select min(t3.[duedate])
from blatz t3
inner join dort t4 on t3.anumerickey = t4.anumerickey
where t4.[somenumbercol] = t2.somenumbercol
and t4.somecode = '01'
and t3.duedate > getdate()) is not null
then (select left(convert(varchar, (select min(t3.[duedate])
from blatz t3
inner join dort t4 on t3.anumerickey = t4.anumerickey
where t4.[somenumbercol] = t2.somenumbercol
and t4.somecode = '01'
and t3.duedate > getdate()), 101), 10))
else
case
when (select min(t0.[duedate])
from sabtz t0
inner join quux t1 on t0.anumerickey = t1.anumerickey
where t0.somenumbercol = t2.somenumbercol
and t0.duedate > getdate()) is not null
then (select left(convert(varchar, (select min(t0.[duedate])
from sabtz t0
inner join quux t1 on t0.anumerickey = t1.anumerickey
where t0.somenumbercol = t2.somenumbercol
and t0.duedate > getdate()), 101), 10))
else
case
when t2.somenumbercol like 'blub%' then 'foo'
when t2.somenumbercol like 'batz%' then 'bar ' + left(convert(varchar, getdate(), 101), 10)
end
end
end
else (select null)
end as [Foobar]
from yyy t1
inner join xxx t2 on t1.somenumbercol = t2.somenumbercol
where ...
It’s the “(SELECT NULL)”.
In the examples below, “(SELECT NULL)” throws the error and “NULL” does not. The “()” casts the NULL as an INT.