• Tom.Thomson (4/8/2010)


    In SQL Server 2005 the IsNull() function will truncate the length of replacement_value to that of check_expression.

    This explanation is wrong. The IsNull function converts to the type of the check_expression, which may involve truncation. It's nonsense to talk about truncating to the length of an expression whose value is null because that length is null. The length of left(null,5) is not 5, it is null.

    I see nothing wrong with the original explanation. It correctly conveys the reason that the result is 'IsUnk' and not 'IsUnknown'.

    It has nothing to do with truncating NULLs. The check_expression here is the result of applying LEFT(..., 5) to a VARCHAR(50) NULLable column. The type of check_expression is clearly VARCHAR(5) NULLable. The replacement_value is implicitly converted to that type, resulting in truncation - exactly what the explanation conveys.

    From the BOL reference included with the explanation: "The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned after it is implicitly converted to the type of check_expression, if the types are different."

    The quick textual explanation is fine, especially so since it includes a BOL reference for further details. You are being overly picky here; this is a QotD, not an academic paper for peer review 😛

    What is interesting here is that left(X,5) delivers an expression of type varchar(5), not an expression of the same type as X. I haven't seen that documented anywhere, and I'm flabbergasted by it. Needless to say I got the wrong answer, and I've learnt this crazy behaviour of Left from it. I guess that makes it a good question - anything that makes me learn is good from my point of view.

    LEFT is documented as returning (n)varchar...what is it exactly that baffles you about an expression with a defined maximum length of 5 being returned as (n)varchar(5)?

    From Expressions (Transact-SQL): When two expressions are combined by using arithmetic, bitwise, or string operators, the operator determines the resulting data type.