当我做一个小任务时,我遇到了一个情况
DECLARE @i INT , @l INT , @desc CHAR(50) SET @l = 1 SET @i = 20 WHILE ( @l <= @i ) BEGIN SELECT 'Test' AS 'Test'+@l SET @l = @l + 1 END
在这段代码中,我想在循环运行时,所有时间列名称都更改为@l的值。
您需要动态生成该语句,并使用EXECUTE或sp_executesql执行该语句。
DECLARE @i INT , @l INT , @desc CHAR(50) SET @l = 1 SET @i = 20 WHILE ( @l <= @i ) BEGIN EXEC ('SELECT ''Test'' AS Test'+@l) SET @l = @l + 1 END
进入动态SQL领域时的推荐阅读:动态SQL的诅咒和祝福
改用sp_executesql:
DECLARE @i INT , @l INT , @desc CHAR(50), @SQL NVARCHAR(100) SET @l = 1 SET @i = 20 WHILE ( @l <= @i ) BEGIN SET @SQL = N'SELECT ''Test'' AS Test'+CAST(@l AS NVARCHAR(10)) EXEC sp_executesql @SQL SET @l = @l + 1 END