2011-11-23 20 views
5

Soy nuevo en los Procedimientos almacenados. Mi tarea es escribir un procedimiento almacenado que primero valide los datos de una tabla temporal y luego inserte los datos en la tabla principal. Para esto estoy planeando iterar sobre cada fila de la tabla temporal, validarlo usando algún otro procedimiento almacenado o función definida por el usuario y luego insertar los datos en la tabla principal.Iteración sin usar el cursor en MYSQL

Mi problema es cómo iterar sobre las filas de la tabla temporal sin usar CURSORS porque son muy lentas y consumen mucha memoria. Quiero usar alguna estructura de bucle en lugar de CURSOR.

Por supuesto, si alguien tiene algún otro algoritmo para el problema anterior, hay sugerencias bienvenidas.

PS: Estoy utilizando MYSQL DB

+2

Tome un vistazo a INSERT ... Instrucción SELECT - http://dev.mysql.com/doc/refman/5.1/en/insert-select.html – Devart

+0

¿Cuál es la regla de validación/c ¿oda? Sería esencial saber si la validación es superficial o si su validación es independiente de la fila. – Nonym

Respuesta

5

Sin el uso de Cursor, se podría repetir el uso de una tabla temporal y una declaración While..Do.

Digamos que tiene dos tablas

CREATE TABLE `user` (
    `id` int(11) NOT NULL auto_increment, 
    `name` varchar(45) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM; 

Y

CREATE TABLE `tmp_user` (
    `id` int(11) NOT NULL auto_increment, 
    `name` varchar(45) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=MyISAM; 

Crear la siguiente rutina, y ajustar el proceso de validación:

DELIMITER $$ 
USE `routines_sample`$$ 
CREATE PROCEDURE `nocursor`() 
BEGIN 
    Declare validId int; 
    Declare validName varchar(45); 

    -- drop the temporary table if exists 
    Drop table if exists `routines_sample`.tmp_validation; 
    -- create the temporary table, here you could use Engine=Memory 
    Create table `routines_sample`.tmp_validation (`id` int not null, `name` varchar(45) not null, `valid` bit(1) not null) Engine=MyISAM; 

    -- insert into the temporary table with a valid flag = 0 (false)  
    Insert into `routines_sample`.tmp_validation (`id`, `name`, `valid`) 
    Select tu.id, tu.name, 0 
    From `routines_sample`.tmp_user tu; 

    -- while exists data to validate on temporary table do something  
    While exists(Select `id` From `tmp_validation` Where `valid` = 0) Do 

    Select `id`, `name` Into @validId, @validName From tmp_validation Where `valid` = 0 Limit 1; 

    -- do your validation 
    Select @validId, @validName; 

    -- don't forget to update your validation table, otherwise you get an endless loop  
    Update `tmp_validation` 
    Set `valid` = 1 
    Where `id` = @validId; 

    END WHILE; 

    -- insert only valid rows to your destination table  
    Insert into `routines_sample`.`user` (`name`) 
    Select `name` From `tmp_validation` 
    Where `valid` = 1; 

    -- drop the temporary table  
    DROP TABLE tmp_validation; 

END$$ 

DELIMITER ; 
+0

gracias ... estaba buscando algo como esto :) –

+0

bueno escuchar eso! @RachitAgrawal podría aceptar la respuesta :) – mbenegas

Cuestiones relacionadas