TSQL string concatenation is not working within WHILE loop

stringtsql

Code bellow is not working, any ideas why?

declare @Counter int
set @Counter = 0
declare @ConcText nvarchar(1000)

while @Counter < 5
begin
    --set @ConcText = @ConcText + cast(@Counter as nvarchar(10)) + N' counter,'
    --set @ConcText = @ConcText + convert(nvarchar(10), @Counter) + N' counter,'
    set @ConcText = @ConcText + N' counter,'
    set @Counter = @Counter + 1
end
print @ConcText --<-- this is null, why  ??

Best Solution

See MSDN: + (String Concatenation) (Transact-SQL):

Just like arithmetic operations that are performed on null values, when a null value is added to a known value the result is typically an unknown value, a string concatenation operation that is performed with a null value should also produce a null result.

So to get things work, it's a good practice to initiate varchar variables immediatly after declare:

DECLARE @ConcText NVARCHAR(1000)
SET @ConcText  = ''

Other way to handle NULL concat issue (in case you don't know if value is NULL or not) - ISNULL or COALESCE:

SET @ConcText = ISNULL(@ConcText, '') + N' counter,'
SET @ConcText = COALESCE(@ConcText, '') + N' counter,'
Related Question