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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With