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.
#set @sql := "insert into foo (name) values(@myname)";? Prepared statements don't usually require quotations around variables, and you've assigned the variable above