2011-11-23 45 views
5

我是存儲過程的新手。 我的任務是編寫一個存儲過程,首先驗證臨時表中的數據,然後將數據插入到主表中。 爲此,我打算迭代臨時表的每一行,使用其他存儲過程或用戶定義的函數對其進行驗證,然後將數據插入到主表中。在MYSQL中不使用遊標的迭代操作

我的問題是如何迭代臨時表的行而不使用CURSORS,因爲它們非常緩慢且耗費內存。我想使用一些循環結構而不是CURSOR

當然,如果任何人有任何其他算法的上述問題,歡迎提出建議。

PS:我使用MYSQL DB

+2

看看INSERT ... SELECT語句 - http://dev.mysql.com/doc/refman/5.1/en/insert-select.html – Devart

+0

什麼是驗證規則/ c頌?瞭解驗證是否粗略或驗證是否與行無關是非常重要的。 – Nonym

回答

5

不使用遊標,你可以重複使用臨時表和While..Do聲明。

比方說,你有兩個表

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

而且

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

創建下列程序,並調整驗證過程:

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

謝謝...我正在尋找這樣的東西:) –

+0

很好聽! @RachitAgrawal你能接受答案:) – mbenegas