Código SQL:
Ver originalDROP DATABASE bd;
CREATE DATABASE bd;
USE bd;
CREATE TABLE tabla1(
id INT PRIMARY KEY AUTO_INCREMENT
);
CREATE TABLE tabla2(
idTabla1 INT
);
INSERT INTO tabla1 VALUES
(DEFAULT),(DEFAULT),(DEFAULT),(DEFAULT),(DEFAULT),(DEFAULT);
INSERT INTO tabla2(idTabla1)VALUES
(1),(3),(6);
SELECT * FROM tabla1;
SELECT * FROM tabla2;
delimiter |
CREATE PROCEDURE buscaEnDosYsiNoHayInserta()
BEGIN
DECLARE done BOOLEAN DEFAULT FALSE;
DECLARE a INT;
-- lee el id de la tabla1 y guarda los valores en c1
DECLARE c1 CURSOR FOR
SELECT id
FROM tabla1;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = TRUE;
OPEN c1;
c1_loop: LOOP
-- fetch c1 into a dice-> a = id)
fetch c1 INTO a;
IF done THEN LEAVE c1_loop; END IF;
-- "busque ese nro en otra tabla(2)"
-- ese nro = a
-- "y si en 2 ese nro no esta que genere un registro nuevo con el valor"
IF(NOT EXISTS(SELECT * FROM tabla2 WHERE idTabla1 = a))THEN
INSERT INTO tabla2 VALUES (a);
END IF;
END LOOP c1_loop;
CLOSE c1;
END
|
CALL buscaEnDosYsiNoHayInserta();
-- --------------------- otros
delimiter |
CREATE PROCEDURE dowhile()
BEGIN
-- DECLARE v1 INT DEFAULT 5;
DECLARE v1 INT DEFAULT 1;
DECLARE v2 INT;
SET v2 = (SELECT COUNT(*) FROM tabla1);
WHILE v2 >= v1 DO
IF(NOT EXISTS(SELECT * FROM tabla2 WHERE idTabla1 = v1))THEN
INSERT INTO tabla2 VALUES (v1);
END IF;
SET v1 = v1 + 1;
END WHILE;
END;
|
delimiter |
CREATE PROCEDURE doiterate()
BEGIN
DECLARE p1 INT DEFAULT 0;
DECLARE v2 INT;
SET v2 = (SELECT COUNT(*) FROM tabla1);
label1: LOOP
SET p1 = p1 + 1;
IF v2 >= p1 THEN
IF(NOT EXISTS(SELECT * FROM tabla2 WHERE idTabla1 = p1))THEN
INSERT INTO tabla2 VALUES (p1);
END IF;
ITERATE label1;
END IF;
LEAVE label1;
END LOOP label1;
-- SET @x = p1;
END;
|
CALL dowhile();
CALL doiterate();