SQL Server loop - how do I loop through a set of records

前端 未结 8 1493
慢半拍i
慢半拍i 2020-11-28 17:54

how do I loop through a set of records from a select?

So say for example I have a few records that I wish to loop through and do something with each record. Here\'s

8条回答
  •  一整个雨季
    2020-11-28 18:20

    By using T-SQL and cursors like this :

    DECLARE @MyCursor CURSOR;
    DECLARE @MyField YourFieldDataType;
    BEGIN
        SET @MyCursor = CURSOR FOR
        select top 1000 YourField from dbo.table
            where StatusID = 7      
    
        OPEN @MyCursor 
        FETCH NEXT FROM @MyCursor 
        INTO @MyField
    
        WHILE @@FETCH_STATUS = 0
        BEGIN
          /*
             YOUR ALGORITHM GOES HERE   
          */
          FETCH NEXT FROM @MyCursor 
          INTO @MyField 
        END; 
    
        CLOSE @MyCursor ;
        DEALLOCATE @MyCursor;
    END;
    

提交回复
热议问题