Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Query in SQL Server

I have a table with 10 columns as col_1,col_2,.... col_10. I want to write a select statement that will select a value of one of the row and from one of these 10 columns. I have a variable that will decide which column to select from. Can such query be written where the column name is dynamically decided from a variable.

like image 674
Vinod Avatar asked Jul 20 '26 00:07

Vinod


1 Answers

Yes, using a CASE statement:

SELECT CASE @MyVariable
       WHEN 1 THEN [Col_1]
       WHEN 2 THEN [Col_2]
       ...
       WHEN 10 THEN [Col_10]
       END

Whether this is a good idea is another question entirely. You should use better names than Col_1, Col_2, etc.

You could also use a string substitution method, as suggested by others. However, that is an option of last resort because it can open up your code to sql injection attacks.

like image 116
Joel Coehoorn Avatar answered Jul 21 '26 18:07

Joel Coehoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!