3

我在 mysql 中编写了一个程序,它从表中返回一个随机值。但是我有很多表,我想多次使用这个过程,所以我添加了作为过程参数名称的表,我想从中获取 rand 值,我将传递给过程的名称也作为参数:

delimiter //

CREATE PROCEDURE randomDefVal(val varchar(50), tableName varchar(50),OUT randomVal varchar(50))

  BEGIN

  SET @tmpTableName = tableName;

  SET @sql_querry = concat('SELECT',@tmpVal,'FROM',@tmpTableName,'ORDER BY rand() LIMIT 1');

  PREPARE stmt FROM @sql_text;

  EXECUTE stmt using @randomVal;

  DEALLOCATE PREPARE stmt;       

END

但是当我运行这段代码时,我有一个错误:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NULL' at line 1

谁能解释我如何将结果存储EXECUTE在变量中?

//解决方案

对于那些与我有同样问题的人,我想展示一个我制作的示例解决方案:

delimiter //

CREATE PROCEDURE tmpProcedure(tableName varchar(20))

BEGIN

DECLARE my_query varchar(60);

DECLARE value varchar(20);

SET @my_query = concat('Select Name FROM ',tableName,' ORDER BY rand() LIMIT 1 INTO @outvar');

PREPARE stmt from @my_query;

EXECUTE stmt;

SET val = (SELECT @outvar); 

END//

我希望它对你有帮助。

4

1 回答 1

2

我在您的代码中看到了一些错误,特别是关于变量名的拼写不同或根本没有声明。查看应该有效的代码:

delimiter //

CREATE PROCEDURE randomDefVal(val varchar(50), tableName varchar(50),OUT randomVal varchar(50))

BEGIN

SET @tmpTableName = tableName;
SET @tmpVal = val;
SET @randomVal = randomVal;

SET @sql_querry = concat('SELECT',@tmpVal,'FROM',@tmpTableName,'ORDER BY rand() LIMIT 1');

PREPARE stmt FROM @sql_text;

EXECUTE stmt using @randomVal;

DEALLOCATE PREPARE stmt;

END 
//
于 2013-04-22T10:37:27.063 回答