Search code examples
sqlsql-server-2008coalesce

Understanding the Syntax for COALESCE


I am trying to understand the below syntax. Can I get some help with this.

DECLARE @StringList VARCHAR(2500); 
SELECT  COALESCE(@StringList + ',','') + CAST(apID as VARCHAR) AS ApIdList FROM testTable

Solution

  • As a result you will get all apID from testTable in VARCHAR

    COALESCE checks if first parameter is NULL then the second parameter will returned. In this line @StringList is always equals NULL

    COALESCE(@StringList + ',','')
    

    So, NULL + ',' = NULL and you will get empty string ('')

    Then empty string + CAST(apID as VARCHAR) and you will get apID as VARCHAR