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