MySQL Cursor无法选择获取变量

时间:2018-02-20 05:06:00

标签: mysql sql mysql-workbench

我正在编写一个游标来循环遍历MySQL模式中的所有表,并获取每列的实际最大列大小。下面是我为它编写的光标。但是我无法遍历表并选择结果集:

DELIMITER // 

DROP PROCEDURE IF EXISTS sp_test //

 CREATE PROCEDURE sp_test ()

BEGIN
   DECLARE exit_loop BOOLEAN;   
   DECLARE mycol VARCHAR(100);
DECLARE mytab VARCHAR(100);
DECLARE cur1 CURSOR FOR 
SELECT column_name,table_name FROM information_Schema.columns where table_schema='TestDB' ;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET exit_loop = TRUE;
DROP TABLE IF EXISTS temp;
CREATE TEMPORARY TABLE temp ( colsize int, colname varchar(1000));
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO mycol,mytab;
INSERT INTO temp (colname,tabname)
select MAX(OCTET_LENGTH(mycol)),IC.column_name from mytab  inner join information_Schema.columns IC on IC.column_name= mycol;
     IF exit_loop THEN
     CLOSE cur1;
     LEAVE read_loop;
 END IF;
   END LOOP read_loop;
 select count(*) from temp;
END;
//
call sp_test

此代码抛出错误:表TestDB.mytab不存在。我无法将光标中的值传递给变量,或者我没有错误地使用它。如果我只使用select而不是INSERT INTO临时表,我会看到每个循环有多个结果集。请纠正我,以实现我的用例。

谢谢

1 个答案:

答案 0 :(得分:1)

正如wchiquito所提到的,你需要使用准备好的SQL语句,它将以下语句作为字符串并执行它。因为在执行语句时,mysql在执行之前不会检索该值,所以我们需要准备一个动态字符串并执行它,

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.CellStyle;

def projectPath = context.expand('${projectDir}') //Where your project resides main project properties 
def path = projectPath + "/userInput.xls" //your inputsheet name

FileInputStream inputStream = new FileInputStream(path)

Workbook wb = WorkbookFactory.create(inputStream)
Sheet sheet1 = wb.getSheet("Sheet Name")
int rows = sheet1.getLastRowNum();
log.info(rows)

希望它有所帮助!