动态MySQL过程无法正常工作

时间:2013-09-23 10:10:29

标签: mysql sql stored-procedures dynamic-sql

Delimiter //
CREATE Procedure SearchTest(IN FieldName varchar(30),IN FieldValue varchar(30))
BEGIN
  SET @query = CONCAT('select count(*) from Some_table_name where ', FieldName,'=',FieldValue);
  PREPARE stmt FROM @query;

  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;

END //
Delimiter ;

mysql> call SearchTest('accession_no','L138362194');
ERROR 1054 (42S22): Unknown column 'L138362194' in 'where clause'

2 个答案:

答案 0 :(得分:0)

您的数据库表没有列L138362194。 您可以通过添加此类列或选择存在的列来解决此问题。

答案 1 :(得分:0)

由于缺少引号而生成错误。这是展示问题的SQL Fiddle

修改存储过程:

DELIMITER //

CREATE PROCEDURE SearchTest(IN FieldName VARCHAR(30), IN FieldValue VARCHAR(30))
BEGIN
  SET @query = CONCAT('SELECT COUNT(*) FROM `some_table_name` WHERE ', FieldName, ' = \'', FieldValue, '\';');
  PREPARE stmt FROM @query;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END //

DELIMITER ;