Search code examples
mysqlvariablesdeclare

MySQL Dynamic query with declares


I would like to ask if it is possible to DECLARE variables in dynamic queries.

i.e.:

CREATE PROCEDURE `storedProcedureName`()
    DETERMINISTIC
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

    SET @i = 0;

    PREPARE dynamicQuery FROM 'DECLARE x INT(11);';
    EXECUTE dynamicQuery;

    PREPARE dynamicQuery FROM 'SET x := ?;';
    EXECUTE dynamicQuery USING @i;

    DEALLOCATE PREPARE dynamicQuery;

    /* More Queries Here */

END

But I'm getting syntax error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE x INT(11)' at line 1

Thanks


Solution

    • First - DECLARE is allowed only inside a BEGIN ... END compound statement.
    • Second - not all stataments can be used in PREPARE statement, more details here - Prepared Statements.

    But you can use something like this -

    SET @text = 'something';
    SET @var = NULL;
    SET @query = 'SELECT ? INTO @var';
    PREPARE s FROM @query;
    EXECUTE s USING @text;
    DEALLOCATE PREPARE s;
    
    SELECT @var;
    +-----------+
    | @var      |
    +-----------+
    | something |
    +-----------+