Ya estoy inscrito ¿Todavía no tienes acceso? Nuestros Planes
Ya estoy inscrito ¿Todavía no tienes acceso? Nuestros Planes
1
respuesta

SP llamado limite_creditos

DELIMITER //

CREATE PROCEDURE limite_creditos() BEGIN DECLARE limite_credito_cliente DECIMAL(10, 2); DECLARE limite_credito_total DECIMAL(10, 2) DEFAULT 0; DECLARE done INT DEFAULT 0;

-- Declarar el cursor
DECLARE cursor_creditos CURSOR FOR
SELECT Limite_Cred
FROM tb_clientes;

-- Declarar el manejador de fin del cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Abrir el cursor
OPEN cursor_creditos;

-- Bucle para recorrer cada fila del cursor
read_loop: LOOP
    FETCH cursor_creditos INTO limite_credito_cliente;
    IF done THEN
        LEAVE read_loop;
    END IF;
    -- Sumar el valor del límite de crédito del cliente al total
    SET limite_credito_total = limite_credito_total + limite_credito_cliente;
END LOOP;

-- Cerrar el cursor
CLOSE cursor_creditos;

-- Mostrar el valor total del límite de crédito
SELECT limite_credito_total AS 'Total de Límite de Crédito';

END;

//

DELIMITER ;

Explicación:

CREATE PROCEDURE limite_creditos(): Crea un procedimiento almacenado llamado limite_creditos.

DECLARE: Declara las variables limite_credito_cliente y limite_credito_total de tipo DECIMAL(10, 2), y la variable done de tipo INT para controlar el fin del cursor.

DECLARE cursor_creditos CURSOR FOR ...: Declara un cursor llamado cursor_creditos para seleccionar el campo Limite_Cred de la tabla tb_clientes.

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1: Declara un manejador que establece done a 1 cuando no se encuentren más filas.

OPEN cursor_creditos: Abre el cursor.

read_loop: LOOP: Inicia un bucle para recorrer cada fila del cursor.

FETCH cursor_creditos INTO limite_credito_cliente: Recupera el valor del campo Limite_Cred en limite_credito_cliente.

IF done THEN LEAVE read_loop: Verifica si done es 1 y, si es así, abandona el bucle.

SET limite_credito_total = limite_credito_total + limite_credito_cliente: Suma el valor del límite de crédito del cliente al total.

CLOSE cursor_creditos: Cierra el cursor.

SELECT limite_credito_total AS 'Total de Límite de Crédito': Muestra el valor total del límite de crédito.

1 respuesta

Hola, Javier ,

Gracias por compartir tu código con nosotros. Recuerda que estamos aquí para ayudarte. Si necesitas ayuda, no dudes en buscarnos en el foro.

¡Gracias nuevamente!

Saludos,

Si este post te ayudó, por favor, marca como solucionado ✓. Continúa con tus estudios!