Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic table name at sql statement

Tags:

mysql

I am trying to executing a mysql query like this

SET @id := '47';
SET @table := @id+'_2013_2014_voucher';
SELECT * FROM @table;
Delete FROM @table where id=@id

It showing error like this

[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@table' at line 1

How I can achieve that?

like image 286
Shaiful Islam Avatar asked Dec 18 '14 08:12

Shaiful Islam


1 Answers

The usage of dynamic table names within the query is best with Prepared Staments, also in mysql for concatenation the function is concat

SET @id := '47';
SET @table := concat(@id,'_2013_2014_voucher');
set @qry1:= concat('select * from ',@table);
prepare stmt from @qry1 ;
execute stmt ;

You can do it for the delete query as well

like image 53
Abhik Chakraborty Avatar answered Oct 09 '22 16:10

Abhik Chakraborty