Reputation: 208042
I have a variable holding the column name. I want to do a select with it like this way
select `@x` from table;
Is it possible?
Upvotes: 1
Views: 116
Reputation: 2472
This should work:
SET @y = CONCAT('SELECT ', @x, ' FROM table;');
PREPARE stmt1 FROM @y;
EXECUTE stmt1;
Upvotes: 1
Reputation: 344531
You can use a prepared statement as follows:
SET @x = 'some_field';
SET @s = CONCAT('SELECT ', @x, ' FROM table;');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Upvotes: 1