我需要编写一个循环,将SQL临时表上的数据一个接一个地传递到存储过程。可以使用以下方法吗?它会消耗大量内存吗?

DECLARE @SomeData AS TABLE(
    Id      INT,
    Name    VARCHAR(MAX),
    Age     INT
)

INSERT INTO @SomeData
        ( Id, Name, Age )
VALUES  ( 1, 'AAAAA', 10 ),
        ( 2, 'BBBBB', 12 ),
        ( 3, 'CCCCC', 13 ),
        ( 4, 'DDDDD', 14 ),
        ( 5, 'EEEEE', 15 );

DECLARE @iterator INT = 0

WHILE @iterator< (SELECT COUNT(Id) FROM @SomeData)
BEGIN
    SELECT *
    FROM @SomeData
    ORDER BY Id
    OFFSET @iterator ROWS
    FETCH NEXT 1 ROWS ONLY

    SET @iterator +=1


    /*Execute a Stored Procedure*/
END

最佳答案

我认为您过一会儿不需要再次(SELECT COUNT(Id)FROM @SomeData),如果表SomeData是一个大数据,它将变慢。您可以这样尝试:

DECLARE @iterator INT = 0
declare @n int = (SELECT COUNT(Id) FROM @SomeData)
WHILE @iterator< @n
BEGIN
    SELECT *
    FROM @SomeData
    ORDER BY Id
    OFFSET @iterator ROWS
    FETCH NEXT 1 ROWS ONLY

    SET @iterator +=1


    /*Execute a Stored Procedure*/
END

关于sql - 可以在循环中使用Offset和Fetch Next吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46482044/

10-11 12:34