自定义mysql函数 - 无法传递参数

时间:2012-03-08 09:59:01

标签: mysql database function

作为标题陈述。这是函数

DELIMITER //
CREATE FUNCTION GetCreateValue( table_name CHAR(64), id_field CHAR(64), name_field CHAR(64), name_value CHAR(64) )
RETURNS INTEGER
BEGIN
    DECLARE ret INTEGER;
    SELECT count(*) INTO ret FROM table_name WHERE name_field = name_value;
    IF ret < 1 THEN
        INSERT INTO table_name SET name_field = name_value;
        SELECT id_field INTO ret FROM table_name WHERE name_field = name_value;
    ELSE    
        SELECT id_field INTO ret FROM table_name WHERE name_field = name_value;
    END IF;
    RETURN ret;
END//
DELIMITER ;

当我运行

之类的东西时
SELECT GetCreateValue('table1', 'ID', 'name', '123456');

我收到表&#34; table_name&#34;的错误不存在。很明显,参数没有通过。为什么呢?

1 个答案:

答案 0 :(得分:0)

SET @qry = 
   CONCAT(
     'SELECT count(*) INTO ret FROM ', table_name, 
      ' WHERE ', name_field, 
      ' = ?');

PREPARE stmt1 FROM @qry;
SET @v = name_value;
EXECUTE stmt1 USING @v;
DEALLOCATE PREPARE stmt1;