我正在尝试以下操作,但我收到以下错误:
ERROR 1054 (42S22): Unknown column 'f' in 'where clause'
我很困惑,因为f
是createtableTest
...
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;
答案 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 ;