2

我正在尝试以下操作,但出现以下错误:

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;
4

1 回答 1

2

由于fis 包含该值,因此需要动态 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 ;

例如,值为fis hello,连接的字符串将产生

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

更新

除了串联之外,您还可以参数化最佳方式的值,例如

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 ;
于 2013-06-03T13:19:15.453 回答