2

I'm trying the following but I'm getting the following error:

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

I'm seriously confused because f is a parameter of 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;
1
  • @JW �? , What exactly did you edit? Was it adding the sql tag? I'm pretty sure the specific question is MySQL specific.
    – Menelaos
    Commented Jun 3, 2013 at 13:31

1 Answer 1

2

Since f is contains the value, a dynamic sql is needed so we can concatenate it with the original query,

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 ;

for example, the value of f is hello, the concatenated string will produce

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

UPDATE

Aside from concatenation, you can also parameterized the value which is the best way, 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 ;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.