Can I use the MySQL PREPARE statement in a function to create a query with the name of a variable table

I want to create a function that has a select query inside that can be used against multiple database tables, but I cannot use the variable as the table name. Can I get around this using the PREPARE statement in a function?

Example:

FUNCTION `TESTFUNC`(dbTable VARCHAR(25)) RETURNS bigint(20)
BEGIN

    DECLARE datereg DATETIME;
    DECLARE stmt VARCHAR(255);

    SET stmt := concat(
      'SELECT dateT FROM', dbTable, 'ORDER BY dateT DESC LIMIT 1');

    PREPARE stmt FROM @stmt;

    EXECUTE stmt;

    RETURN dateT;

END $$

Thanks in advance for any input.

+3
source share
1 answer

Instead stmt varchar(255), use @stmt:

...
 DECLARE datereg DATETIME;
  SET @stmt = concat(
  'SELECT dateT FROM', dbTable, 'ORDER BY dateT DESC LIMIT 1');
  ....
+3
source

Source: https://habr.com/ru/post/1750383/


All Articles