Mysql动态地从游标中获取值

时间:2015-07-17 05:44:53

标签: mysql stored-procedures triggers

DELIMITER $$
CREATE TRIGGER t1_trigger BEFORE DELETE ON  t1
FOR EACH ROW
BEGIN

-- Declaration DECLARE str VARCHAR(1024) DEFAULT ""; DECLARE c1 VARCHAR(64) DEFAULT ""; DECLARE c2 VARCHAR(64) DEFAULT ""; DECLARE c3 VARCHAR(64) DEFAULT ""; DECLARE x int ; DECLARE var VARCHAR(64) DEFAULT "var"; DECLARE i_counter INT DEFAULT 1;

-- Find the number of columns of a table. DECLARE cur1 CURSOR FOR select count(*) from information_schema.columns where table_schema='plsqls' and table_name='t1'; -- Get the Column values of table DECLARE cur CURSOR FOR SELECT * FROM t1 WHERE t1.id = OLD.ID; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -- Create Dynamic Variables of a table OPEN cur1; FETCH cur1 INTO x; while i_counter < x DO SET str =CONCAT(str,CONCAT(var,i_counter,',')); SET i_counter=i_counter+1; end while; CLOSE cur1; -- Assign the coulmn values to the dynamic variables. -- Here i get the column names instead of column values. OPEN cur; ins_loop: LOOP FETCH cur INTO str; IF done THEN LEAVE ins_loop; END IF; INSERT INTO t1_log VALUES (null, str); END LOOP; CLOSE cur; END;$$

问题:
这里的问题我们不能发现&#39; str&#39;动态应用。
当我删除表格(t1)但我面对下面的错误是&#39;错误的FETCH变量数量&#39;。 -

1 个答案:

答案 0 :(得分:0)

您得到的错误是'FETCH变量数不正确'。
这是因为您选择表t1中的所有列作为
    DECLARE cur CURSOR FOR SELECT * FROM t1 WHERE t1.id = OLD.ID;
但只取1个值作为
    FETCH cur INTO str;

解决方案

  1. 使用光标选择所需的列为
    DECLARE cur CURSOR FOR SELECT id FROM t1 WHERE t1.id = OLD.ID;
    1. 获取您选择的所有列为
      FETCH cur INTO x, y, z;