我们可以使用SQL Server中的while循环将记录存储在临时表中吗?

Lia*_*san 2 sql sql-server stored-procedures

我有一种使用以下循环将记录存储在临时表中的方案。

例如

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
    PRINT @intFlag
    SET @intFlag = @intFlag + 1
    select @intFlag datas
    into #tempped
END
GO
Run Code Online (Sandbox Code Playgroud)

有可能这样做吗?

Sql*_*Zim 5

您可以创建临时表并将insert其从循环中放入。例如:

create table #tempped (datas int);

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
    PRINT @intFlag;

    insert into #tempped (datas)
    select @intFlag;

    SET @intFlag = @intFlag + 1;
END
GO
Run Code Online (Sandbox Code Playgroud)

我认为这个问题是抽象的,如果您对性能感兴趣,那么while循环,递归cte或游标并不是最有效的解决方案。而是使用数字或理货表格。

进一步阅读: