title: T-SQL While Loop and concatenation
body: <p>I have  a SQL query that is supposed to pull out a record and concat each to a string, then output that string. The important part of the query is below.</p>
  
  <pre><code>DECLARE @counter int;
  SET @counter = 1;
  
  DECLARE @tempID varchar(50);
  SET @tempID = '';
  
  DECLARE @tempCat varchar(255);
  SET @tempCat = '';
  
  DECLARE @tempCatString varchar(5000);
  SET @tempCatString = '';
  
  WHILE @counter &lt;= @tempCount
  BEGIN
  
      SET @tempID = (
      SELECT [Val]
      FROM #vals
      WHERE [ID] = @counter);
  
      SET @tempCat = (SELECT [Description] FROM [Categories] WHERE [ID] = @tempID);
      print @tempCat;
  
      SET @tempCatString = @tempCatString + '&lt;br/&gt;' + @tempCat;
      SET @counter = @counter + 1;
  
  END
  </code></pre>
  
  <p>When the script runs, <code>@tempCatString</code> outputs as null while <code>@tempCat</code> always outputs correctly. Is there some reason that concatenation won't work inside a While loop? That seems wrong, since incrementing <code>@counter</code> works perfectly. So is there something else I'm missing?</p>