简体   繁体   中英

How to use SQL alias with variable

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM