MySQL存储过程错误 - 从参数名称创建表

时间:2013-06-03 13:15:42

标签: mysql sql stored-procedures

我正在尝试以下操作,但我收到以下错误:

ERROR 1054 (42S22): Unknown column 'f' in 'where clause'

我很困惑,因为fcreatetableTest ...

的参数
CREATE PROCEDURE createtableTest
(
tname2 varchar(20),
f varchar(20)
)
BEGIN
DROP TABLE IF EXISTS tname2;
CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like f;
END;

1 个答案:

答案 0 :(得分:2)

由于f包含值,因此需要动态sql,因此我们可以将其与原始查询连接,

DELIMITER $$

CREATE PROCEDURE createtableTest(IN tname2 varchar(20),IN f varchar(20))
BEGIN
    DROP TABLE IF EXISTS tname2;
    SET @sql = CONCAT('CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like ''%',f,'%''');
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END $$

DELIMITER ;

例如,f的值为hello,连接的字符串将生成

CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like '%hello%'

<强>更新

除了连接之外,您还可以参数化最佳方式的值,ex

DELIMITER $$

CREATE PROCEDURE createtableTest(IN tname2 varchar(20),IN f varchar(20))
BEGIN
    DROP TABLE IF EXISTS tname2;
    SET @sql = CONCAT('CREATE TABLE tname2 as SELECT * FROM data WHERE group_name like ?');
    PREPARE stmt FROM @sql;
    SET @val = CONCAT('%', f, '%');
    EXECUTE stmt USING @val;
    DEALLOCATE PREPARE stmt;
END $$

DELIMITER ;