T-SQL While Loop and concatenation

Posted by JustinT on Stack Overflow See other posts from Stack Overflow or by JustinT
Published on 2009-01-16T20:20:51Z Indexed on 2010/04/18 0:13 UTC
Read the original article Hit count: 569

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.

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 <= @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 + '<br/>' + @tempCat;
    SET @counter = @counter + 1;

END

When the script runs, @tempCatString outputs as null while @tempCat always outputs correctly. Is there some reason that concatenation won't work inside a While loop? That seems wrong, since incrementing @counter works perfectly. So is there something else I'm missing?

© Stack Overflow or respective owner

Related posts about sql-server

Related posts about sql