如果存在,update else insert,在存储过程中使用游标只返回1行

a64a0gku  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(393)

我有两个表api(columns-api、api\u context、api\u id-->主键)和api\u request\u summary(columns-api\u context)。我需要在curhittest1表中插入与特定api\u id相关的api\u上下文的重复次数。也就是说,我需要获得列api\上下文中某个值重复多少次的计数,并用api\ id插入它。这两个表都有多行,因此我使用游标在表中循环。我可以正确地将值插入到表中,但我需要检查curhittest1表中是否已经存在该api\u id,如果是,则更新,如果不是,则插入。

DELIMITER //
CREATE PROCEDURE curhit12()

BEGIN

 DECLARE done INT DEFAULT FALSE;
 DECLARE apiId, noOfHits int(11);
 Declare apiContext varchar(255);

 DECLARE cur1 CURSOR FOR Select api_id from api;

 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;     

  OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO apiId;

    IF done THEN
      LEAVE read_loop;
    END IF; 

    select api_context into apiContext from api where api_id =apiId;  

    SELECT COUNT(*) FROM api_request_summary WHERE api_context=apiContext into noOfHits;

 IF exists (SELECT * FROM curhittest1 WHERE apiid = apiId) THEN

   UPDATE curhittest1
                      SET noofhits=noOfHits                        
                      WHERE apiid = apiId;
 ELSE

  insert into curhittest1(apiid,noofhits) values (apiId,noOfHits);
 END IF;

  END LOOP;

  CLOSE cur1;

END//
DELIMITER

当我使用以下代码时,curhittest1表中只添加了一行。当在没有游标的sql过程中使用完全相同的代码时,它会显示出来,因此我假设在使用游标时需要做一些不同的操作。如何将所有值准确地添加到表中?

wfauudbj

wfauudbj1#

第二个 INTO 循环中的句子可能触发 NOT FOUND 处理程序。
更改此行:

SELECT COUNT(*) FROM api_request_summary WHERE api_context=apiContext into noOfHits;

对此:

SET noOfHits = (SELECT COUNT(*) FROM api_request_summary 
                WHERE api_context=apiContext);
vpfxa7rd

vpfxa7rd2#

它在使用insert后工作了。。。在重复密钥更新时。对这里感兴趣的人来说是代码

DELIMITER //
CREATE PROCEDURE curhit12()

BEGIN

 DECLARE done INT DEFAULT FALSE;
 DECLARE apiId, noOfHits int(11);
 Declare apiContext varchar(255);    
 DECLARE cur1 CURSOR FOR Select api_id from api;    
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;     

  OPEN cur1;

read_loop: LOOP
    FETCH cur1 INTO apiId;

    IF done THEN
      LEAVE read_loop;
    END IF; 

    select api_context into apiContext from api where api_id =apiId;  

SET noOfHits = (SELECT COUNT(*) FROM api_request_summary 
                WHERE api_context=apiContext);

INSERT INTO api_hits (api_id,no_of_hits) VALUES (apiId,noOfHits)
   ON DUPLICATE KEY UPDATE no_of_hits=noOfHits;

  END LOOP;

CLOSE cur1;

END//
DELIMITER

相关问题