当我正在完成一项小任务时,我遇到了一个情况
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。
的值答案 0 :(得分:4)
您需要动态构建语句并使用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世界时的推荐阅读:The Curse and Blessings of Dynamic 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