Estructuras de control

Estructuras alternativas y repetitivas en MySQL

Programación de Bases de Datos (6.1.- Características y conceptos básicos)

Estructuras de control en MYSQL

Estructuras de control selectivas en MySQL:

Ejemplo: IF en la base de datos de Proyectos

DELIMITER $$
CREATE OR REPLACE PROCEDURE ponerSalario(IN _codigo CHAR(3), IN _salario INT)
BEGIN
    DECLARE _actual INT;

    SELECT salario INTO _actual FROM empleado WHERE cdemp = _codigo;
    IF (_actual >= _salario) THEN
        SELECT CONCAT('El salario ya es de ', _actual) as INFO;
    ELSE
        UPDATE empleado SET salario = _salario WHERE cdemp = _codigo;
        SELECT CONCAT('El salario se ha actualizado a  ', _salario) as INFO;
    END IF;
END
$$
DELIMITER ;

Ejecución

CALL ponerSalario('A03', 1000);
CALL ponerSalario('A03', 4000);

Estructuras de control iterativas en MySQL:

Ejemplo: FOR en la base de datos de Proyectos

DELIMITER $$
CREATE OR REPLACE PROCEDURE listaNombres()
BEGIN
    DECLARE _lista TEXT DEFAULT '';
    FOR _fila IN (SELECT * FROM empleado where nombre IS NOT NULL)
        DO SET _lista := CONCAT (_lista, ', ', _fila.nombre);
    END FOR;
    SELECT _lista as Nombres;
END
$$
DELIMITER ;

Ejecución

CALL listaNombres();

Ejemplo: WHILE Loop

Crear la base de datos test y la tabla calendars

CREATE DATABASE test;

USE test;

DROP TABLE IF EXISTS calendars;

CREATE TABLE calendars(
    date DATE PRIMARY KEY,
    month INT NOT NULL,
    quarter INT NOT NULL,
    year INT NOT NULL
);

Crar el procedimiento InserCalendar

DELIMITER $$

CREATE PROCEDURE InsertCalendar(IN currentDate DATE)

BEGIN
        INSERT INTO calendars(date, month, quarter, year)
            VALUES(currentDate, MONTH(currentDate), QUARTER(currentDate), YEAR(currentDate));		
END

$$

DELIMITER ;

Crear el procedimiento loadDates

DELIMITER $$

CREATE PROCEDURE loadDates(
    startDate DATE, 
    day INT
)
BEGIN
    
    DECLARE counter INT DEFAULT 1;
    DECLARE currentDate DATE DEFAULT startDate;

    WHILE counter <= day DO
        CALL InsertCalendar(currentDate);
        SET counter = counter + 1;
        SET currentDate = DATE_ADD(currentDate ,INTERVAL 1 day);
    END WHILE;

END

$$

DELIMITER ;

Ejecutar loadDates

CALL loadDates('2024-04-08', 7);

SELECT * FROM calendars;

 

Más información:

MySQL Stored Procedures Tutorial

IF statement – show you how to use the IF THEN statement in stored procedures.

CASE statement – introduce you to the CASE statements including simple CASE and searched CASE statements.

LOOP – learn how to execute a list of statements repeatedly based on a condition.

REPEAT Loop – show you how to execute a loop until a search condition is true.

LEAVE statement – guide you on how to exit a loop immediately.

Deja una respuesta