如何使用表中的值执行存储过程

时间:2014-02-24 09:42:22

标签: sql sql-server tsql sql-server-2012

我有一个proc,它根据某些条件从表中检索数据并将其插入到临时表中。

我现在想要使用临时表中的值来执行另一个proc,这个值将包含大约2000个条目。

我可以在一个EXEC中执行此操作并从#Temp表中选择所有条目吗?

我想做这样的事情:

DECLARE @return_value int
EXEC    @return_value = [dbo].[prInsertAssessmentLevels]
        @WFRouteItemID = (SELECT WFRouteItemID FROM #WFsNotInWFAssessmentLevel),
        @UOB = (SELECT UOB FROM #WFsNotInWFAssessmentLevel WHERE WFRouteItemID = @WFRouteItemID),
        @Life = (SELECT Life FROM #WFsNotInWFAssessmentLevel WHERE WFRouteItemID = @WFRouteItemID),
        @Health = (SELECT Health FROM #WFsNotInWFAssessmentLevel WHERE WFRouteItemID = @WFRouteItemID),
        @Disability = (SELECT Disability FROM #WFsNotInWFAssessmentLevel WHERE WFRouteItemID = @WFRouteItemID),
        @CreatedUserID = 1

2 个答案:

答案 0 :(得分:1)

您想要做的更像是逐行遍历表并使用所有行值执行存储过程。让我给你一个基于游标的方法的模板:

DECLARE curName CURSOR FOR 
      SELECT col1, col2, col3 
      FROM your_table

OPEN curName
      FETCH NEXT FROM curName INTO @pk
      WHILE @@FETCH_STATUS = 0
      BEGIN
            EXEC your_Procedure (@par1 = @col1, @par2 = @col2, @par3 = @col3)
            FETCH NEXT FROM curName INTO @col1, @col2, @col3
      END
CLOSE curName

DEALLOCATE curName

答案 1 :(得分:1)

你需要一个光标

DECLARE @return_value int
DECLARE @WFRouteItemID  int /* Or whatever the correct Type is*/
DECLARE @UOB            int /* Or whatever the correct Type is*/
DECLARE @Life           int /* Or whatever the correct Type is*/
DECLARE @Health         int /* Or whatever the correct Type is*/
DECLARE @Disability     int /* Or whatever the correct Type is*/
DECLARE @CreatedUserID  int /* Or whatever the correct Type is*/

DECLARE PARAM_CURSOR CURSOR FOR 
SELECT WFRouteItemID, UOB, Life, Health, Disability, CreatedUserID
FROM #WFsNotInWFAssessmentLevel 


OPEN PARAM_CURSOR 
FETCH NEXT FROM PARAM_CURSOR  INTO @WFRouteItemID, @UOB, @Life, @Health, @Disability, @CreatedUserID
WHILE @@FETCHSTATUS = 0
BEGIN

EXEC    @return_value = [dbo].[prInsertAssessmentLevels],@WFRouteItemID, @UOB, @Life, @Health, @Disability, @CreatedUserID     

FETCH NEXT FROM PARAM_CURSOR  INTO @WFRouteItemID, @UOB, @Life, @Health, @Disability, @CreatedUserID
END
CLOSE PARAM_CURSOR 
DEALLOCATE PARAM_CURSOR