Skip to content
Advertisement

Unpredictable behaviour in nested CASE statement

I’m unable to figure out why the control goes always to a statement irrespective of inside CASE condition.

A normal SQL statement works, but with my table it does not work.

And results in below error:

Explicit conversion from data type text to int is not allowed.

Advertisement

Answer

Explicit conversion from data type text to int is not allowed.

This error message seems pretty clear. Why are you using a text data type? It is deprecated. To quote from the documentation:

IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

So, your code on the real table is executing the ELSE condition, which causes it to fail. In the code with constants, ELSE condition is not failing. Why is this?

I think the error is being caught in the compilation phase of the query. The error does not occur in the second example, because SQL Server is short-circuiting the query, recognizing that the ELSE is not needed. The code in the second example is simply not compiled.

I am pretty sure you would see the same behavior if you replaced the code with 1 / 0 (although the other part of the case expression would need to change as well for the types to be compatible).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement