Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select dynamic column value from a table?

I have a table called "TableA" which has the following records:

TableA:

      ID       Jan       Feb
     ----     -----     -------
      1      '01/12'    '04/12'

Here I want to select any one of the column value from the table. But the column name is assigned to a variable. We don't know the exact column name.

For Example:

    Declare @Month VARCHAR(20)
    SET @Month = 'Feb'

    Select @Month from TableA

It gives the Output as follows:

    'Feb'

But the Desired Output is '04/12'

How to get the desired output?

like image 842
thevan Avatar asked Feb 13 '26 05:02

thevan


1 Answers

Use UNPIVOT

select months
from TableA
unpivot 
(months for m in (Jan, Feb)) pvt
where m=@month

It's a much safer solution than dynamic SQL as it isn't vulnerable to a SQL Injection attack

like image 125
podiluska Avatar answered Feb 14 '26 17:02

podiluska