How To have Dynamic SQL in MySQL Stored Procedure

前端 未结 3 1803
无人共我
无人共我 2020-11-21 22:10

How do you build and use dynamic sql in a MySQL stored procedure?

3条回答
  •  一整个雨季
    2020-11-21 22:43

    I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

    Here is an example:

    mysql> PREPARE stmt FROM 
        -> 'select count(*) 
        -> from information_schema.schemata 
        -> where schema_name = ? or schema_name = ?'
    ;
    Query OK, 0 rows affected (0.00 sec)
    Statement prepared
    mysql> EXECUTE stmt 
        -> USING @schema1,@schema2
    +----------+
    | count(*) |
    +----------+
    |        2 |
    +----------+
    1 row in set (0.00 sec)
    mysql> DEALLOCATE PREPARE stmt;
    

    The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

    Here is a good link about this:

    Don't forget to deallocate the stmt using the last line!

    Good Luck!

提交回复
热议问题