1

There is a table named as customer like this:

|  Name  |  Age  |  Balance  |
------------------------------
|  Kevin |  25   |  150000   |
|  Bob   |  33   |  350000   |
|  Anna  |  27   |  200000   |

Simply, to select "Name" column we can use:

SELECT Name FROM customer

Now, I want to do that by using a variable like this:

SET @temp = 'Name'
SELECT @temp FROM customer

The result I get:

|  @temp  |
-----------
|   Name  |

The result I want is same like the normal select:

|  Name  |
----------
|  Kevin |
|  Bob   |
|  Anna  |

I am expecting this will run the same like "SELECT Name From Customer", so it basically run the SELECT from a variable value.

I also use a function returned value to do the same thing, but I get the similar result. For example, there is function called CustName(Value):

SELECT CustName(A) // Return : 'Name' 
FROM   customer;

This will give me result:

|  CustName(A)  |
-----------------
|      Name     |

Is there any way that MySQL will run "Name" normally like when I basically write "Select Name from customer" ?

Reza Satnaz
  • 101
  • 2
  • 15

1 Answers1

1

What you're saying you're looking for is dynamic sql.. it's generally not a fabulous idea as you're trying to vary a part of a query that the database wants to be fixed, for performance reasons. You'll also struggle to make use of your sql in a client app if it's expecting a string of a username, but then the user supplied 'birthday' as the thing to select and your client gets a date instead

If you're hell bent on doing it, this SO post gives more detail: How To have Dynamic SQL in MySQL Stored Procedure

I must ask you to consider though, that this is a broken solution you've devised, to some other problem. It might be better to post the other problem as solving it may prove more productive

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • It is fine, since I will use this only for migrating some data. The problem is, the string that I want to put is not on WHERE = ?, but SELECT ? – Reza Satnaz Aug 04 '17 at 06:47
  • It's not so much about using ? to specify things that will vary, it's about putting the sql in a string and executing it.. build the exact sql you want, in a string and prepare it, see comment on accepted answer from Stefan Rogin for one example, see answer from Tim solo (#2 highest answer) for another example.. both use CONCAT to build sql, it's not so much about the ? As it is about the CONCAT :) – Caius Jard Aug 05 '17 at 04:05