Search code examples
sqlt-sqlcursor

TSQL set concatenating varchar during cursor


When debugging, @buildEvents gets filled the first time it enters the loop but then never gets concatenated the next time around. Is this possible inside of a cursor?

OPEN @BusinessCursor;
FETCH NEXT FROM @BusinessCursor INTO  @BusinessName;

WHILE @@FETCH_STATUS = 0
BEGIN

set @buildEvents = @buildEvents + @BusinessName

FETCH NEXT FROM @BusinessCursor INTO   @BusinessName;
END

CLOSE @BusinessCursor;
DEALLOCATE @BusinessCursor;     


      select @buildEvents
      return

Any ideas on how to get @buildEvents concatenated with @BusinessName? The data im passing through is html data for an email.


Solution

  • You are not doing one of 2 things probably:

    1. when you declare @buildEvents assign it an empty string:

      declare @buildEvents varchar(max) = ''

    2. in your loop check for null in @BusinessName:

      set @buildEvents = @buildEvents + ISNULL(@BusinessName, '')