0

I have a table which stores the total income on monthly basis. The columns are named as column_1, column_2, ... , column_12. Each month I need to update the value on the column corresponding to the month. For example, Jan = column_1, Feb = column_2 etc. How to dynamically select the column and update the required column every month in a single update statement instead of writing multiple if else in PLSQL? Any help would be appreciated.

1
  • Perhaps dynamic SQL is appropriate? Commented Apr 22, 2021 at 11:31

1 Answer 1

2

Quite painfully. You should probably fix your data model, so each month's data is stored in a row not in a column.

But if you are stuck with someone else's bad data model, you can use:

update t
    set month_1 = (case when extract(month from sysdate) = 1 then :val else month_1 end),
        month_1 = (case when extract(month from sysdate) = 2 then :val else month_2 end),
        . . .   -- repeat for all months
    where <whatever other conditions you have>;

In other words, you are updating all columns. However, 11 of them will get the value they already have.

Sign up to request clarification or add additional context in comments.

1 Comment

This looks fair enough. No other option, I am stuck with an existing model and cannot make changes to the structure now. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.