MySQL - 如何存储执行结果

时间:2013-04-22 10:21:32

标签: mysql sql executequery

我在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//

我希望它会对你有所帮助。

1 个答案:

答案 0 :(得分: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 
//