Is it possible to execute a stored procedure over a set without using a cursor?

前端 未结 7 919
遥遥无期
遥遥无期 2020-12-15 18:55

I would like to execute a stored procedure over each row in a set without using a cursor with something like this:

SELECT EXEC dbo.Sproc @Param1 = Table1.i

7条回答
  •  失恋的感觉
    2020-12-15 19:21

    This loop works, but it was slow for my SP. I think the correct answer is by HLGEM, your best bet is to write a better bulk query.

    DECLARE @id INT
    SET @id = 0
    
    DECLARE @max INT
    SELECT TOP 1 @max = TableID
    FROM dbo.Table
    ORDER BY TableID desc
    
    -- loop until BREAK
    -- this is how you can perform a DO-WHILE loop in TSQL
    WHILE (1 = 1) 
    BEGIN
        SELECT      
            TOP 1 @id = TableID
            FROM dbo.Table
            WHERE TableID > @id 
    
        IF @id IS NOT NULL
        BEGIN        
            -- call you SP here
            PRINT @id        
        END
    
        -- break out of the loop once the max id has been reached
        IF @id = @max BREAK 
    END
    

提交回复
热议问题