我已经创建了一个触发器,它创建了一个动态查询。并且我已经尝试过执行它' 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 这是我做的功能 返回更换( SUBSTRING( SUBSTRING_INDEX(str,delim,pos), CHAR_LENGTH( SUBSTRING_INDEX(str,delim,pos - 1) )+ 1 ), delim, '' )
答案 0 :(得分:0)
根据我的理解,您必须首先从字符串中生成一个准备好的语句才能执行它。因此,以下部分代码应该只替换EXEC q
:
PREPARE thequery FROM q;
EXECUTE thequery;
答案 1 :(得分:0)
使用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
答案 2 :(得分:0)
我已经编写了一个存储过程来执行动态构造的sql语句。
SET @index := 7;
CALL statement(CONCAT('SELECT ', @index));
CREATE PROCEDURE statement(IN dynamic_statement TEXT)
BEGIN
SET @dynamic_statement := dynamic_statement;
PREPARE prepared_statement FROM @dynamic_statement;
EXECUTE prepared_statement;
DEALLOCATE PREPARE prepared_statement;
END
;