MariaDB将聚合函数名称作为存储过程参数传递

时间:2017-11-29 15:40:52

标签: sql database stored-procedures mariadb aggregate-functions

我正在编写存储过程,其中汇总函数名称列名称作为参数并返回值(例如:' sum' ,' age')返回值(SELECT SUM(age)FROM myTable))

我的代码:

CREATE PROCEDURE sample (IN name VARCHAR(10), IN col VARCHAR(30), OUT result INT) 
BEGIN
    SELECT CONCAT( name , '(', col, ') ') INTO result FROM myTable;
END$

2 个答案:

答案 0 :(得分:0)

将其设为FUNCTION

return CONCAT('SELECT ', name, '(', col, ') FROM myTable;');

答案 1 :(得分:0)

使用Prepared Statements

CREATE PROCEDURE sample (IN name VARCHAR(10), IN col VARCHAR(30), OUT result INT) 
BEGIN
    SET @sql := '';
    SET @ret := 0;

    SELECT CONCAT('SELECT ', name,  '(', col, ') INTO @ret FROM myTable') INTO @sql FROM DUAL;
    PREPARE STMT from @sql;
    EXECUTE STMT;

    SELECT @ret INTO result FROM DUAL;

    DEALLOCATE PREPARE STMT;     
END