Hopefully Microsoft will add language support that would allow more elegant solutions. For example, for similar problems related specifically to conversion errors Microsoft introduced the TRY_CAST, TRY_CONVERT and TRY_PARSE in SQL Server 2012. The functions are similar to their CAST, CONVERT and PARSE counterparts, only when the expression isn’t convertible to the target type, the functions return a NULL instead of causing the query to fail.
Proposal: add support for a function like TRY_EXPRESSION (or other appropriate name) that accepts a scalar expression as input and returns the result when it is evaluated successfully, and NULL when it isn’t instead of causing the query to fail.
As an example, the above two queries would be rewritten as follows, and this way would be guaranteed not to fail:
SELECT keycol, val
FROM dbo.T1
WHERE val*1/1 > 0 AND TRY_EXPRESSION(LOG(val)) <= 10;
SELECT keycol, val
FROM dbo.T1
WHERE val*1/1 <> 0 AND TRY_EXPRESSION(43112609/val) < 100;
Thanks for your consideration,
Itzik