我写了这个函数:
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);' 如何返回值,这将是'EXECUTE'语句的结果?
答案 0 :(得分: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