Why I'm getting this error?
CREATE DEFINER=`root`@`localhost` PROCEDURE `selectrecords`(tablename varchar(50))
begin
set @table_name=tablename;
set @sql_text=concat('Select * from @table_name');
prepare statement from @sql_text;
execute statement;
deallocate prepare statement;
end
Error:
....to use near '@table_name' at line 1
My code is correct but I don't understand why....
I think you mean,
CREATE PROCEDURE `selectrecords`(tablename varchar(50))
begin
set @sql_text = concat('Select * from ', tablename);
prepare statement from @sql_text;
execute statement;
deallocate prepare statement;
end
even in dynamic sql, you cannot parameterized table names as well as column names so your only choice is to concatenate in with the string. Only values can be place in a place holder.
UPDATE 1
CREATE PROCEDURE `selectrecords`(tablename varchar(50))
begin
set @val = idnumber;
set @sql_text = concat('Select * from ', tablename, ' WHERE id = ?');
prepare statement from @sql_text;
execute statement USING @val;
deallocate prepare statement;
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With