How do I automatically reset a sequence's value to 0 every year in Oracle 10g?

后端 未结 7 848
既然无缘
既然无缘 2021-01-02 22:09

As in the question, how do I automatically reset an Oracle sequence\'s value back to 0 every year in Oracle 10g?

I\'m using the sequence to generate an identifier i

7条回答
  •  -上瘾入骨i
    2021-01-02 22:39

    Just throwing this out there as an idea:

    If you want a solution that requires no ongoing DDL (i.e. no dropping and creating or resetting sequences), or even any jobs, you could consider something like this (this is in principle only, I haven't tested this approach but I'm sure it'll work):

    1. Create a single sequence.

    2. Create a reference table, with one row for each year, e.g.

      YEARS (year NUMBER(4,0) PRIMARY KEY, starting_value NUMBER)

    3. When you get NEXTVAL from the sequence, you then have to subtract the starting_value when queried from the YEARS table for the current year. If the year is not found, a new row should be inserted (i.e. the first process run in any given year will insert the new value).

    e.g. a function, e.g. get_year_starting_value (pn_year IN NUMBER) RETURN NUMBER could query this table and return the starting_value for the given year; if it gets NO_DATA_FOUND, it could call a procedure to insert it using the NEXTVAL from the sequence (committed in an autonomous transaction so that the new value is immediately available to other sessions, and so that the function doesn't fail due to the side effect)

    Probably not a solution for all cases, but I think this approach may help in at least some scenarios.

提交回复
热议问题