Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL While Loop and concatenation

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?

like image 614
JustinT Avatar asked Jan 16 '09 20:01

JustinT


People also ask

Can you use concatenate in SQL?

In SQL, you can also concatenate numerical data from the table in the same way as we concatenate strings. The CONCAT function can also be used to join numeric values.

Can you do a WHILE loop in SQL?

The while loop in SQL begins with the WHILE keyword followed by the condition which returns a Boolean value i.e. True or False. The body of the while loop keeps executing unless the condition returns false. The body of a while loop in SQL starts with a BEGIN block and ends with an END block.

What is the alternative for WHILE loop in SQL Server?

CTE vs SQL Server WHILE Loop Database developers usually try to solve the previous problem using CTEs. CTE stands for Common Table Expressions which is a temporary named result set.


2 Answers

Looks like it should work but for somereason it seems to think @tempCatString is null which is why you are always getting a null value as nullconcatenated to anything else is still null. Suggest you try with COALESCE() on each of the variables to set them to " " if they are null.

like image 118
HLGEM Avatar answered Oct 06 '22 00:10

HLGEM


this would be more efficient....

select @tempCatString = @tempCatString + Coalesce(Description,'') + '<br/>' from Categories...

select @fn

also look at concat_null_yields_null as an option to fix your concatenation issue, although I would avoid that route

like image 37
keithwarren7 Avatar answered Oct 05 '22 22:10

keithwarren7