如何在while循环中连接两个变量

问题描述 投票:0回答:1

我想用while循环构造一个'union all'查询。

我已经尝试过+ =连接但不起作用。

DECLARE @cnt1 int , @concat nvarchar(max), @qry nvarchar(500);
SET @cnt1 = 1;
WHILE @cnt1 < 99 
BEGIN 
SET @qry = 'select name_' + CAST(@cnt1 AS CHAR) + ' , name2_' + CAST(@cnt1 AS CHAR) + ', m.state1 FROM table1 P left join table2 M on M.name = P.name_' + CAST(@cnt1 AS CHAR) + ' where p.nb > 1'; 
SET @cnt1 = @cnt1 + 1; 
SET @concat += ' UNION ALL ' + @qry 
END 
EXEC sp_executesql @concat 

@concat在循环结束时仍为空...

谢谢你

tsql stored-procedures concatenation
1个回答
2
投票

由于@concat未初始化,因此默认值为null。将值与null连接会导致null,因此循环中没有进展。将其初始化为空字符串:

declare @Concat as NVarChar(max) = N'';

将解决问题。

提示:CharVarCharNCharNVarChar的默认长度大多数情况下是一个字符。当它是CastConvert的目标类型时,它是30个字符。最佳实践:始终指定长度。

© www.soinside.com 2019 - 2024. All rights reserved.