2

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.

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.