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 ??
See MSDN: + (String Concatenation) (Transact-SQL):
So to get things work, it’s a good practice to initiate varchar variables immediatly after declare:
Other way to handle NULL concat issue (in case you don’t know if value is NULL or not) – ISNULL or COALESCE: