0

I'm attempting to insert a string into a table via a prepared statement. My specific use case is complicated, but I've reduced the problem down to its essence. Consider the following code:

drop table if exists foo;
create table foo (
  id int primary key,
  name varchar(10)
);
set @myname := "Bob";
insert into foo (name) values(@myname); # this DOES work

#set @sql := CONCAT("insert into foo (name) values((", @myname, ")"); # does not work
#set @sql := CONCAT("insert into foo (name) values((\'", @myname, "\')"); # does not work
#set @sql := CONCAT("insert into foo (name) values(('", @myname, "')"); # does not work
#set @sql := "insert into foo (name) values(''Alice'')"; # does not work
#set @sql := "insert into foo (name) values('Alice')"; # does not work

#set @sql := "insert into foo (name) values(Alice)"; # this DOES work
prepare stmt from @sql;
execute stml;
select * from foo;

Of course doing an insert without a prepared statement works. However, all the of commented lines fail to work (except the last which doesn't use the variable) with error code 1064.

How do I insert the variable @myname into a table using a prepared statement? This code needs to run in a stored procedure, so I'm not looking for a solution that is written in another language.

2
  • Did you try #set @sql := "insert into foo (name) values(@myname)";? Prepared statements don't usually require quotations around variables, and you've assigned the variable above Commented Aug 27, 2015 at 23:25
  • @nomistic I did try that and that doesn't work either. Commented Aug 27, 2015 at 23:55

1 Answer 1

1

Not much to comment here other than adding the auto_increment, and some extra left parenthesis stuff. And the typo near the last line.

create table foo (
  id int auto_increment primary key, -- EDIT done here
  name varchar(10)
);
set @myname := "First Bob";
insert into foo (name) values(@myname);

set @myname:="Second Bob";
set @sql := CONCAT("insert foo(name) values('", @myname, "')");
select @sql; -- eyeball it

prepare stmt from @sql;
execute stmt;
select * from foo;
+----+------------+
| id | name       |
+----+------------+
|  1 | First Bob  |
|  2 | Second Bob |
+----+------------+
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Drew, It was the typo that caused the problem.

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.