0

I have create a trigger which is create a dynamic query.and execute it i had tried 'EXECU q' but it does not work. how can i run/execute that dynamic query.

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

This is Trigerr this is Function which i made RETURN REPLACE( SUBSTRING( SUBSTRING_INDEX(str , delim , pos) , CHAR_LENGTH( SUBSTRING_INDEX(str , delim , pos - 1) ) + 1 ) , delim , '' )

Shadow
  • 33,525
  • 10
  • 51
  • 64

3 Answers3

5

I've written a stored procedure to execute dynamically constructed sql statements.

Usage

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

Implementation

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 ;
Community
  • 1
  • 1
Nae
  • 14,209
  • 7
  • 52
  • 79
0

From my understanding you must make a prepared statement from your string first in order to execute it. So the following partial code should work in replacement for just EXEC q:

PREPARE thequery FROM q;
EXECUTE thequery;
fyaa
  • 646
  • 1
  • 7
  • 25
0

use prepare statement to execute your dynamic query

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
Ankit Agrawal
  • 2,426
  • 1
  • 13
  • 27