Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
barnabeck
Posting Yak Master
236 Posts |
Posted - 2012-06-28 : 07:26:27
|
| I need to select column-names dynamically.The columnnames for the Items I need to address from my database are Item1, Item2,... to Item19; the number that specifies the Item is index_number.How can I do something likeselect Item+index_number ?The data is imported data from an excel document; the document is not available anymore and the reference from the cells position to the the cell content has to be established in this way... sounds odd, but that's the way it is.Regards,Martin |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-06-28 : 07:35:03
|
Since you have only 19 columns, my preferred approach would be to use a case expression like shown below. You can also use dynamic SQL, but most experts on this forum would try to dissuade from using dynamic SQL if it can be avoidedDECLARE @INDEX INT = 2;SELECT CASE WHEN @INDEX = 1 THEN Item1 WHEN @INDEX = 2 THEN Item2 -- WHEN INDEX = 3 THEN Item3 -- and so on upto 19. ENDFROM YourTable |
 |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-06-28 : 08:15:59
|
| Just want to mention that in my previous reply, I assumed that you have the same data type for all 19 columns. If that is not the case, the CASE expression would not work correclty. |
 |
|
|
|
|
|