抵消& Fetch Next可以在循环中使用吗?

时间:2017-09-29 04:55:08

标签: sql sql-server loops stored-procedures

我需要编写一个循环来将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

1 个答案:

答案 0 :(得分:1)

我认为你之后不需要(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