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

前端 未结 7 920
遥遥无期
遥遥无期 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:15

    Take a look at this answer using dynamic SQL. Here is what looks like based on your query.

    DECLARE @TSQL NVARCHAR(MAX) = ''
    SELECT @TSQL = @TSQL + N'EXEC dbo.Sproc ' + id + '; 
    ' -- To insert a line break
    FROM Table1
    EXEC sp_executesql @TSQL
    

    This equals to the following if you PRINT @TSQL. Note that how the line break is inserted.

    EXEC dbo.Sproc id1; 
    EXEC dbo.Sproc id2; 
    EXEC dbo.Sproc id3;
    ...
    

    If you don't need a stored procedure, it can be easier. I once had a need to update a table based on each row (Code is the column name, and [Value] the value) from a view. Because the view is dynamic and returns different rows each time, and hence different column-value pairs. I re-wrote the query without using any stored procedure.

    DECLARE @TSQL NVARCHAR(MAX), @Id VARCHAR(10) = 50
    
    SELECT @TSQL = COALESCE(@TSQL + '''
    ,','') + Code + ' = ''' + [Value] 
    FROM view
    WHERE Id = @Id
    
    SET @TSQL = N'UPDATE tableName
    SET ' + @TSQL + ''' 
    WHERE Id = ' + @Id
    PRINT @TSQL
    --EXEC SP_EXECUTESQL @TSQL
    

    PRINT @TSQL:

    UPDATE tableName
    SET Discussed = 'Yes'
    ,Other = 'Blue'
    ,IntakeRating = 'H: < $25k'
    ,IntakeValueEstimate = '25'
    ,OpportunityDecision = 'Intake'
    ,Fee = '33 1/3'
    ,Fee2 = '40'
    ,IsManager = 'Yes' 
    WHERE Id = 50
    

提交回复
热议问题