Search code examples
sqlcoalesce

Assign Column Name for Simple Coalesce Statement


While attempting to create a list of all ID's made since _____ I am able to get the results I want from the following:

DECLARE @BoID varchar(max)

SELECT @BoID = COALESCE(@BoID + ', ', '') + 
   CAST(ApplicationID AS varchar(10)) 
FROM BoList as "ID"
WHERE CreatedDate > '2017-07-01 18:14:09.210' 

However, I am having issues with establishing a column name for the above statement. Where does the as "ID" need to be located at in order to give the above result a column name of "ID"?


Solution

  • As the query stands now, you are giving the table BoList an alias of "ID" instead of the column. Since you are selecting the value into a variable there is no output. You can do it like this...

    SELECT COALESCE(@BoID + ', ', '') + 
       CAST(ApplicationID AS varchar(10)) as "ID"
    FROM BoList 
    WHERE CreatedDate > '2017-07-01 18:14:09.210'
    

    Or if you really do need to stash the value in a variable to return later as part of another query...

    DECLARE @BoID varchar(max)
    
    SELECT @BoID = COALESCE(@BoID + ', ', '') + 
       CAST(ApplicationID AS varchar(10)) 
    FROM BoList
    WHERE CreatedDate > '2017-07-01 18:14:09.210' 
    
    SELECT @BoID AS "ID", other columns... FROM whatever