gpt4 book ai didi

Mysql 程序。更新并选择

转载 作者:行者123 更新时间:2023-11-30 00:53:04 24 4
gpt4 key购买 nike

我有一个过程调用,它更新一组数据,然后返回该数据集以供渲染。一切正常,除了我不能同时进行这两项操作。如果我进行更新,则该过程将不会返回任何值,反之亦然。我看到一些建议使用 temptables 的答案,但我找不到如何检索数据集。我很感激任何帮助,即使是为了改进我的查询。

CREATE DEFINER=`root`@`localhost` PROCEDURE `prueba`(IN `idUsuario` INT)
MODIFIES SQL DATA

BEGIN

DECLARE flag INT DEFAULT FALSE;
DECLARE done INT DEFAULT FALSE;
DECLARE idNotificacion INT DEFAULT 0;
DECLARE cont INT DEFAULT 0;
DECLARE resultset CURSOR FOR SELECT id FROM notificaciones WHERE involvedA_idUsuario=idUsuario AND active=1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN resultset;

SET @query = "SELECT * FROM notificaciones n WHERE n.id IN('null'";

the_loop: LOOP
FETCH resultset INTO idNotificacion;
IF done THEN
LEAVE the_loop;
END IF;
SET cont = cont + 1;
SET flag = TRUE;
SET @query = CONCAT(@query," , " ,idNotificacion);
UPDATE notificaciones SET active=0 WHERE id=idNotificacion;
END LOOP the_loop;

CLOSE resultset;

IF flag THEN
SET @query = CONCAT(@query, ")");
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;

END

最佳答案

你真的需要光标吗?像这样的选项,也许会有用:

/* Procedure structure for procedure `prueba` */

/*!50003 DROP PROCEDURE IF EXISTS `prueba` */;

DELIMITER $$

CREATE PROCEDURE `prueba`(`idusuario` INT)
BEGIN
DECLARE `ids` LONGTEXT DEFAULT NULL;
SELECT GROUP_CONCAT(`id`) INTO `ids`
FROM `notificaciones`
WHERE `involveda_idusuario` = `idusuario` AND `active` = 1;
IF (`ids` IS NOT NULL) THEN
SET @`stmt` := CONCAT('UPDATE `notificaciones`
SET `active` = 0
WHERE `id` IN (', `ids`, ')');
PREPARE `exec` FROM @`stmt`;
EXECUTE `exec`;
SET @`stmt` := CONCAT('SELECT `id`, `involveda_idusuario`, `active`
FROM `notificaciones` `n`
WHERE `n`.`id` IS NULL OR `n`.`id` IN (', `ids`, ')');
PREPARE `exec` FROM @`stmt`;
EXECUTE `exec`;
DEALLOCATE PREPARE `exec`;
END IF;
END$$

DELIMITER ;

您必须小心GROUP_CONCAT和系统变量 group_concat_max_len .

SQL Fiddle demo

关于Mysql 程序。更新并选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20805577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com