如何在mysql服务器中执行动态sql字符串作为查询?

lp0sw83n  于 2021-06-23  发布在  Mysql
关注(0)|答案(3)|浏览(365)

我已经创建了一个触发器,它是创建一个动态查询,并执行它我已经尝试了'execu q',但它不工作。如何运行/执行该动态查询。

BEGIN
    DECLARE a INT Default 0 ;
    DECLARE str  VARCHAR(255);
    DECLARE q VARCHAR(500);

    SET q = 'insert into '+new.master_name+' values(';

    simple_loop: LOOP
        SET a=a+1; 
        SET str = SPLIT_STRING(new.remarks,"|",a); 
        SET q = CONCAT(q,str+',');
        SET q = LEFT(q, LENGTH(q) - 1);
        IF str='' THEN
                LEAVE simple_loop; 
            END IF;

    END LOOP simple_loop; 
    SET q = CONCATE(q,');');

    EXEC q
END

这是trigerr这是我用return替换的函数(substring(substring\u index(str,delim,pos),char\u length(substring\u index(str,delim,pos-1))+1),delim,')

csga3l58

csga3l581#

我编写了一个存储过程来执行动态构造的sql语句。

用法

SET @index := 7;
CALL eval(CONCAT('SELECT ', @index));

实施

DELIMITER $$

CREATE PROCEDURE eval(IN dynamic_statement TEXT)
  BEGIN
      SET @dynamic_statement := dynamic_statement;
      PREPARE prepared_statement FROM @dynamic_statement;
      EXECUTE prepared_statement;
      DEALLOCATE PREPARE prepared_statement;
  END$$

DELIMITER ;
zkure5ic

zkure5ic2#

据我所知,为了执行它,你必须先用你的字符串做一个准备好的语句。所以下面的部分代码应该可以代替 EXEC q :

PREPARE thequery FROM q;
EXECUTE thequery;
vjrehmav

vjrehmav3#

使用prepare语句执行动态查询

BEGIN
    DECLARE a INT Default 0 ;
    DECLARE str  VARCHAR(255);
    DECLARE q VARCHAR(500);
    DECLARE q1 VARCHAR(500);
    DECLARE q2 VARCHAR(500);

    SET @q = 'insert into '+new.master_name+' values(';

    simple_loop: LOOP
        SET a=a+1; 
        SET str = SPLIT_STRING(new.remarks,"|",a); 
        SET q = CONCAT(@q,str+',');
        SET q1 = LEFT(q, LENGTH(q) - 1);
        IF str='' THEN
                LEAVE simple_loop; 
            END IF;

    END LOOP simple_loop; 

    SET q2 = CONCATE(q1,');');
    PREPARE stmt FROM q2;
    EXECecute stmt;
    deallocate PREPARE stmt;
END

相关问题