• JohnG (11/20/2008)


    Additionally,

    1. It doesn't properly support a legitimate value of -1 as -1 is being used to indicate that the value is not numeric.

    2. An explicit CAST is needed in the assignment part ("THEN") of the CASE statement as for some quirky reason, a value of '123.45' cannot be implicitly converted to DECIMAL(38,19) when it is part of a CASE statement. Error: Conversion failed when converting the varchar value '123.45' to data type int. Yet a direct assignment (IntRef = ExtRef) works fine! (SQL Server 2005 SP2)

    Hi John,

    Well, your first point is by design. If the design calls for -1 being used to represent incorrect format, you can't blame the code for using -1 for two purposes. Apparently, the assumption here is that -1 will never be a real value in the data. 🙂

    WRT the second point - the reason is not "quirky" at all. The data type of the CASE is always equal to a data type used in one of the WHEN clauses or the ELSE clause, with the choice being determined by the rules of precedence. In the posted code, data types used were varchar(9) (from the ExtRef column) and int (from the constant -1, as a constant with no decimal point and within the range of integers is always considered to be int). Of these, int has the highest precedence, so the varchar is converted. And after that, the result of the CASE is converted to decimal(38,19) for the purpose of assiging it to the IntRef column.

    I'll gladly admit that I missed this double conversion myself. Fortunately I did not lose a point over it as I am well aware of the limitations of ISNUMERIC(), but it wasn't until I read the comments here that I noticed the code would choke on "really" valid decimal numbers as well due to the hidden conversion to integer.

    Good question!


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/