Reputation: 27
I have the following code:
set @a='city_name';
select place_names from table1 tbl1 inner join table2 tbl2
on tbl1.city_name = tbl2.city_name
Here I need to use variable @a
with alias tbl1
. Something like tbl1.@a
and tbl2.@a
.
How can I do this?
Thanks in advance.
Upvotes: 2
Views: 6310
Reputation: 562951
Syntax, including column names and other identifiers, must be fixed at the time the statement is parsed.
The only way to use a user variable as part of SQL syntax is to use a prepared statement, so you can build a SQL statement as a string before it is parsed.
SET @a='city_name';
SET @sql=CONCAT('select place_names from table1 tbl1 inner join table2 tbl2
on tbl1.', @a, ' = tbl2.', @a);
PREPARE stmt1 FROM @sql;
EXECUTE stmt;
Upvotes: 3