1

我写了这个函数:

delimiter //

CREATE FUNCTION randomDefVal(val varchar(30), tableName varchar(30)) 
    returns varchar(30)

    BEGIN

        SET @query = concat('SELECT ',val,' FROM ',tableName,' ORDER BY rand() LIMIT 1;');
        SET @result = NULL;
        PREPARE stmt1 FROM @query;
        return (EXECUTE stmt1);

    END//

但我在最后一行有一个错误:

SQL Error (1336): Dynamic SQL is not allowed in stored function or trigger

这表明我不能写 'return (EXECUTE stmt1);' 如何返回值,这将是“执行”语句的结果?

4

1 回答 1

1

我认为您想要的是SELECT ... INTO。所以你会在你的BEGIN和里面有这样的东西END(注意我没有测试过这段代码):

BEGIN
    DECLARE var_name VARCHAR(30);
    SET var_name = '';
    SELECT val INTO var_name FROM tableName ORDER BY rand() LIMIT 1;
    RETURN var_name;
END
于 2013-04-25T19:43:49.073 回答