0

Following is my code of MySQL Stored Function.

DELIMITER $$

USE `mac_db`$$

DROP FUNCTION IF EXISTS `moving_average`$$

CREATE DEFINER=`root`@`localhost` FUNCTION `moving_average`(`table_name` VARCHAR(255),`column_name` VARCHAR(255),`order_column` VARCHAR(255),`row_cnt` INT) RETURNS DOUBLE

    DETERMINISTIC

BEGIN   DECLARE result_avg DOUBLE DEFAULT 0;

    SELECT AVG(`column_name`) INTO result_avg FROM table_name ORDER BY order_column DESC LIMIT row_cnt;

    RETURN result_avg;

    END$$

DELIMITER ;

I am calling the function as follows:

SELECT moving_average('my_table','my_col','id',4);

I am getting the following error.

Table 'mac_db.table_name' doesn't exist

Please help to resolve the error.

3
  • You cannot parameterize an identifier (such as a table or column name), so you have to use dynamic SQL -- prepare. Commented Feb 27, 2018 at 11:41
  • OK. Can you please edit the code and guide Commented Feb 27, 2018 at 11:43
  • 1
    @VrajeshDoshi This Answer may help you out :) Commented Feb 27, 2018 at 11:43

1 Answer 1

0

table_name is a parameter not the name of table.

replace you proc parameter as below:

DELIMITER $$

USE mac_db$$

DROP FUNCTION IF EXISTS moving_average$$

CREATE DEFINER=root@localhost FUNCTION  moving_average(@table_name VARCHAR(255),@column_name VARCHAR(255),@order_column VARCHAR(255),@row_cnt INT) RETURNS DOUBLE

DETERMINISTIC
BEGIN DECLARE result_avg DOUBLE DEFAULT 0;

SELECT AVG(@column_name) INTO result_avg FROM @table_name ORDER BY @order_column DESC LIMIT @row_cnt;

RETURN result_avg;

END$$
DELIMITER ;
Sign up to request clarification or add additional context in comments.

2 Comments

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '@table_name VARCHAR(255),@column_name VARCHAR(255),@order_column VARCHAR(255),@r' at line 1
try removing @sign while defining variable. @table_name VARCHAR(255) with table_name VARCHAR(255)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.