Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

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

An 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.

like image 874
aHunter Avatar asked Oct 24 '25 06:10

aHunter


1 Answers

Instead of stmt varchar(255) use @stmt:

...
 DECLARE datereg DATETIME;
  SET @stmt = concat(
  'SELECT dateT FROM', dbTable, 'ORDER BY dateT DESC LIMIT 1');
  ....
like image 102
a1ex07 Avatar answered Oct 26 '25 20:10

a1ex07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!