我想用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在循环结束时仍为空...
谢谢你
由于@concat
未初始化,因此默认值为null
。将值与null
连接会导致null
,因此循环中没有进展。将其初始化为空字符串:
declare @Concat as NVarChar(max) = N'';
将解决问题。
提示:Char
,VarChar
,NChar
或NVarChar
的默认长度大多数情况下是一个字符。当它是Cast
或Convert
的目标类型时,它是30个字符。最佳实践:始终指定长度。