• The query uses [font="Comic Sans MS"]IsNull(@MaleNames + ', ','') + [name][/font].

    When @MaleNames is NULL, [font="Comic Sans MS"]@MaleNames + ', '[/font] is NULL as well, so the ISNULL kicks in and replaces the NULL with an empty string, to which [name] is concatenated. This leaves us with a single name and no comma.

    When @MaleNames is not NULL (but, for instance, a single name and no comma), [font="Comic Sans MS"]@MaleNames + ', '[/font] adds a comma to that name, the ISNULL does nothing, and then [Name] is concatenated - so now we have two names, seperated by a comma.

    After that it continues to add ', ' and a name to the string, until processing stops.

    DISCLAIMER: This description is based on the assumption that SQL Server will process the rows one by one and not reset the variable in between; this is often observed but undocumented behaviour and should not be relied on. Other behaviour can happen anytime (and has in fact sometimes been observed).


    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/