Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic column name selection in MySql

I am stuck in Mysql today with the dynamic column name need in mysql select statement. Let me explain:

sql> select name1 from namescollection. 
sql> select name2 from namescollection. 
sql> select name3 from namescollection. 

So namescollection table has three columns having name1, name2, name3 I would like to query this table in my stored procedure being 1,2,3 as dynamic and would be passed as a variable, but on the simple sql too when i query:

SELECT concat('name','1') FROM `namescollection` 

name1 ----- name1 rather fetching name1 field's value.

Can any suggest on this, the right function i need to use rather concat though I know its right to output name1 when I am calling concat but I want to use it as column name.

like image 320
Luckyy Avatar asked Jul 28 '12 06:07

Luckyy


People also ask

What is dynamic column in MySQL?

Dynamic columns is a feature that allows one to store different sets of columns for each row in a table. It works by storing a set of columns in a blob and having a small set of functions to manipulate it.


1 Answers

What you can do is use a prepared statement within your stored procedure which will allow you to execute a string query:

As a simple example:

DELIMITER //
CREATE PROCEDURE selname (IN col VARCHAR(20))
BEGIN
  SET @sql = CONCAT('SELECT ', col, ' FROM tbl');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END//
DELIMITER ;

Test it out with this SQLFiddle Demo

like image 192
Zane Bien Avatar answered Nov 09 '22 08:11

Zane Bien