tags:

views:

34

answers:

1

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.

A: 

Instead of stmt varchar(255) use @stmt:

...
 DECLARE datereg DATETIME;
  SET @stmt = concat(
  'SELECT dateT FROM', dbTable, 'ORDER BY dateT DESC LIMIT 1');
  ....
a1ex07
This does indeed appear to work but only in a Stored Procedure which does not help for what I was trying to because I wanted to use it in a function or a trigger.
aHunter
Yes, it works in SP only. @Wrikken mentioned it in his comment to your question. Personally I missed the point that you use FUNCTION, not SP...
a1ex07