• Good question, but a BIG mistake in the explanation!!

    "COALESCE returns a datatype from the first non-null value in the statement depending on data type precedence"

    The datatype of the first non-null value is irrelevant. COALESCE will first consider the data types of ALL arguments, then apply data type precedence rules to them, and then use the result as the data type of the result. Here is a simple repro:

    DECLARE @number int, @text varchar(20);

    SET @number = NULL;

    SET @text = 'three';

    SELECT COALESCE(@number, @text);

    go

    DECLARE @number int, @text varchar(20);

    SET @number = NULL;

    SET @text = 'three';

    SELECT COALESCE(@text, @number);

    The integer parameter is null; the first (and only) non-null parameter is varchar. And yet, both the COALESCE statements fail because they try to convert the result to an integer - the highest precedence datatype of the two.


    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/