how to pick a column based on a parameter

  • Hi, I have 12 columns, one for each month, the column has a float value I need to retrieve based on a parameter that my stored procedure will receive, along with other 5 columns that have descriptions, ids and other stuff

    What is the more efficient way to structure the query? or do i have to repeat the query 12 times?

  • You need to normalise your table.

    _____________
    Code for TallyGenerator

  • as a short-term fix (until you implement the above recommendation, perhaps with a table holding yearid, monthid, your float value and a FK back to the original table), you can use the simple case statement:

    select
     tab.id
    ,tab.description
    ,tab.stuff
    ,@month M
    ,case @month
     when @month = 1 then tab.M1
     when @month = 2 then tab.M2
    ...
     when @month = 12 then tab.M12 M_total
    from
    whatevertable tab

     

     

    Tim Wilkinson

    "If it doesn't work in practice, you're using the wrong theory"
    - Immanuel Kant

  • sorry, should be:
     
    select
     tab.id
    ,tab.description
    ,tab.stuff
    ,@month M
    ,case @month
     when 1 then tab.M1
     when 2 then tab.M2
    ...
     when 12 then tab.M12 M_total
    from
    whatevertable tab

     

    I half-changed it from searched to simple

    Tim Wilkinson

    "If it doesn't work in practice, you're using the wrong theory"
    - Immanuel Kant

  • sorry again, should be:
    select
     tab.id
    ,tab.description
    ,tab.stuff
    ,@month M
    ,case @month
     when 1 then tab.M1
     when 2 then tab.M2
    ...
     when 12 then tab.M12
    end M_total
    from
    whatevertable tab

    I promise to check my code properly in future...

    Tim Wilkinson

    "If it doesn't work in practice, you're using the wrong theory"
    - Immanuel Kant

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply