MySQL如何循环存储过程?

时间:2012-02-24 17:40:39

标签: mysql stored-procedures for-loop cursor

我有一个名为 Evaluate(something1,something2); 的存储过程 Evaluate将获取一些参数,在数据库中搜索它们并将结果插入结果表中。

现在我希望创建一些类型的存储过程,它将不断调用Evaluate来迭代整个逗号分隔的文件。这可能吗?

伪代码

assessEntireFile()
{
  loop file
    Evaluate(single line from file)
   end loop
}



**The work flow of assessEntireFile() will be as followed:**
1. call assessEntireFile()
   --assessEntireFile will load and iterate over an input file (line-by-line)
2. each iteration will call Evaluate() on that line
   --evualte() will produce results in a table
3. complete

2 个答案:

答案 0 :(得分:1)

DELIMITER $$

CREATE PROCEDURE assessEntireTable()
  READS SQL DATA
BEGIN

-- Declare variables according to your table/file structure
  DECLARE field1 int DEFAULT 0;
  DECLARE field2 VARCHAR(250) CHARACTER SET utf8;
-- /Declare variables according to your table/file structure

  DECLARE done int DEFAULT 0;
  DECLARE currentrow CURSOR FOR SELECT * FROM assessEntireFileTmp; 
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1;

  OPEN currentrow;
-- Adapt next line according to your table/file structure
  FETCH currentrow INTO field1,field2, ... ;
  WHILE done=0 DO
-- Adapt next 2 lines according to your table/file structure
     CALL Evaluate(field1, field2, ...);
     FETCH currentrow INTO field1,field2, ... ;
  END WHILE;
END $$

CREATE PROCEDURE assessEntireFile()
BEGIN
  DROP TABLE IF EXISTS assessEntireFileTmp;
  CREATE TABLE assessEntireFileTmp (

--  Your needed structure here

  );
  LOAD DATA INFILE '<file_name>'
     INTO TABLE assessEntireFileTmp
--   More needed parameters here
  ;

  CALL assessEntireTable();

  DROP TABLE assessEntireFileTmp;
END $$  

DELIMITER ;

答案 1 :(得分:-1)

你可以在SQL中使用while循环

@count = 1
while @count < 1000
    begin
    update etc
@count = @count + 1
end

http://msdn.microsoft.com/en-us/library/ms178642.aspx