开发者社区> 问答> 正文

如何在存储过程的循环值中传递参数并将结果集转储到临时表中?

如何创建存储过程,可以将其@CandidatelistID作为参数传递给下面的现有存储过程逻辑。

我正在循环CandidateID和,CandidateListID并usp_ApplyRankingRules在循环内运行存储过程以获取Weightage每个循环的存储过程。

然后,而不是插入和更新表中的值- RPT_CandidateCardReport我想在临时表中加载相同的字段。当我这样做时,出现以下错误-

(0 row(s) affected)

(0 row(s) affected)
Msg 208, Level 16, State 0, Procedure usp_RPT_CandidateCardReporttest, Line     24 [Batch Start Line 53]
Invalid object name '#tempRPTCandidateCardReport'.

数据存在于我尝试循环的表中,并应在底部显示temptable select语句的结果。

CREATE PROCEDURE [dbo].[usp_RPT_CandidateCardReporttest]     @candidateListIDs varchar(36)
    AS
    BEGIN
declare @candidateListID varchar(36)
declare @candidateID varchar(36)
declare @var_weightage decimal
declare @listcount INT = (SELECT COUNT(1) FROM CandidateList_Candidates)
declare @loopcount INT = 1


IF OBJECT_ID('tempdb..#tmpListCandidate') IS NOT NULL DROP TABLE #tmpListCandidate
SELECT CandidateListID, CandidateID, ROW_NUMBER()OVER(ORDER BY cl.CandidateID) AS Id INTO #tmpListCandidate 
FROM CandidateList_Candidates cl
where CandidateListID = @candidateListIDs

WHILE(@loopcount <= @listcount)
    BEGIN
        SET @candidateListID = (SELECT CandidateListID FROM #tmpListCandidate WHERE Id = @loopcount)
        SET @candidateID = (SELECT CandidateID FROM #tmpListCandidate WHERE Id = @loopcount)

        EXEC usp_ApplyRankingRules @candidateListID, @candidateID, @var_weightage OUTPUT

        IF EXISTS (SELECT 1 FROM #tempRPTCandidateCardReport WHERE listID = @candidateListID AND candidateID = @candidateID)
            BEGIN
                UPDATE #tempRPTCandidateCardReport SET weightage = @var_weightage WHERE listID = @candidateListID AND candidateID = @candidateID
            END
        ELSE
            BEGIN    
                INSERT INTO #tempRPTCandidateCardReport (listID, candidateID, weightage)
                    VALUES (@candidateListID, @candidateID, @var_weightage) 
            END
        SET @loopcount = @loopcount + 1
    END

select listid,candidateid,weightage from #tempRPTCandidateCardReport

IF OBJECT_ID('tempdb..#tmpListCandidate') IS NOT NULL 
BEGIN 
    DROP TABLE #tmpListCandidate
    DROP TABLE #tempRPTCandidateCardReport
END

结束

sql

展开
收起
祖安文状元 2020-01-04 15:35:28 643 0
1 条回答
写回答
取消 提交回答
  • 我不会在存储过程的几个方面发表评论,但我认为您想要:

    CREATE PROCEDURE [dbo].[usp_RPT_CandidateCardReporttest] ( 
       @candidateListID varchar(36)
    )
    AS
    BEGIN
        . . . 
        SELECT CandidateListID, CandidateID, 
               ROW_NUMBER() OVER (ORDER BY cl.CandidateID) AS Id 
        INTO #tmpListCandidate 
        FROM CandidateList_Candidates cl
        WHERE CandidateListID = @CandidateListID OR @CandidateListID IS NULL;
    
        SELECT @ListCounct = COUNT(*)
        FROM #tmpListCandidate ;
    
        . . .
    END;
    
    2020-01-04 15:36:25
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载