Pentium10
Pentium10

Reputation: 208042

How to SELECT a column held in a local variable in MySQL?

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

Answers (2)

skyman
skyman

Reputation: 2472

This should work:

SET @y = CONCAT('SELECT ', @x, ' FROM table;');
PREPARE stmt1 FROM @y;
EXECUTE stmt1;

Upvotes: 1

Daniel Vassallo
Daniel Vassallo

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

Related Questions