How to prevent duplication on a column with condition

Hello everyone,
I need some advice here. At work, we have an Oracle APEX app that allow user to add new records with the automatic increment decision number based on year and group name.
Says if they add the first record , group name AA, for year 2012, they get decision number AA 1 2013 as their displayed record casein the report page.
The second record of AA in 2013 will be AA 2 2013.
If they add about 20 records , it will be AA 20 2013.
The first record for 2014 will be AA 1 2014.
However, recently , we get a user complaint about two records from the same group name have the same decision number.
When I looked into the history table, and find that the time gap between 2 record is just about 0.1 seconds.
Besides, we have lookup table that allows admin user to update the Start Sequence number with the restraint that it has to be larger than the max number of the current group name of the current year.
This Start sequence number and group name is stored together in a table.
And in some other special case,user can add a duplicate decision number for related record. (this is a new function)
The current procedure logic to add new record on the application are
_Get max(decision_number) from record table with chosen Group Name and current year.
_insert into the record table the new entered record with decision number + 1
_ update sequence number to the just added decision number.
So rather than utitlising APEX built-in automatic table modification process, I write a procedure that combine all the three process.
I run some for loop to continuously execute this procedure, and it seems it can autotically generate new unique decision number with time gap about 0.1 second.
However, when I increase the number of entry to 200, and let two users run 100 each.
If the time gap is about 0.01 second, Duplicate decision numbers appear.
What can I do to prevent the duplication ?
I cannot just apply a unique constraint here even for all three columns with condition, as it can have duplicate value in some special condition. I don't know much about using lock and its impact.
This is the content of my procedure
create or replace
PROCEDURE        add_new_case(
  --ID just use the trigger
  p_case_title IN varchar2,
  p_year IN varchar2,
  p_group_name IN VARCHAR2,
  --decisionnumber here
  p_case_file_number IN VARCHAR2,
  --active
  p_user IN VARCHAR2
AS
  default_value NUMBER;
    caseCount NUMBER;
  seqNumber NUMBER;
  previousDecisionNumber NUMBER;
BEGIN
  --execute immediate q'[alter session set nls_date_format='dd/mm/yyyy']';
  SELECT count(*)
        INTO caseCount
        FROM CASE_RECORD
        WHERE GROUP_ABBR = p_group_name
        AND to_number(to_char(create_date, 'yyyy')) = to_number(to_char(date_utils.get_current_date, 'yyyy'));
        SELECT max(decision_number)
        INTO previousDecisionNumber
        FROM CASE_RECORD
        WHERE GROUP_ABBR = p_group_name
        AND to_number(to_char(create_date, 'yyyy')) = to_number(to_char(date_utils.get_current_date, 'yyyy'));
        IF p_group_name IS NULL
        THEN seqNumber := 0;
        ELSE   
        SELECT seq_number INTO seqNumber FROM GROUP_LOOKUP WHERE ABBREVATION = p_group_name;
        END IF;
    IF caseCount > 0 THEN
           default_value := greatest(seqNumber, previousdecisionnumber)+1;
    ELSE
           default_value := 1;
    END IF; 
  INSERT INTO CASE_RECORD(case_title, decision_year, GROUP_ABBR, decision_number, case_file_number, active_yn, created_by, create_date)
  VALUES(p_case_title, p_year, p_group_name, default_value, p_case_file_number, 'Y', p_user, sysdate );
  --Need to update sequence here also
  UPDATE GROUP_LOOKUP
  SET SEQ_NUMBER = default_value
  WHERE ABBREVATION = p_group_name;
  COMMIT;
EXCEPTION
WHEN OTHERS THEN
    logger.error(p_message_text => SQLERRM
                ,p_message_code => SQLCODE
                ,p_stack_trace  => dbms_utility.format_error_backtrace
    RAISE;
END;
Many thanks in advance,
Ann

Why not using a sequence for populating the decision_number column ?
Sequence values are guaranteed to be unique so there's no need to lock anything.
You'll inevitably have gaps and no different groups will have the same decision_number in common.
Having to deal with consecutive numbers fixations you can proceed as
with
case_record as
(select 2012 decision_year,'AA' group_abbr,1 decision_number from dual union all
select 2012,'BB',2 from dual union all
select 2012,'AA',21 from dual union all
select 2012,'AA',22 from dual union all
select 2012,'BB',25 from dual union all
select 2013,'CC',33 from dual union all
select 2013,'CC',34 from dual union all
select 2013,'CC',36 from dual union all
select 2013,'BB',37 from dual union all
select 2013,'AA',38 from dual union all
select 2013,'AA',39 from dual union all
select 2013,'BB',41 from dual union all
select 2013,'AA',42 from dual union all
select 2013,'AA',43 from dual union all
select 2013,'BB',45 from dual
select decision_year,
       group_abbr,
       row_number() over (partition by decision_year,group_abbr order by decision_number) decision_number,
       decision_number sequence_number -- not shown (noone needs to know you're using a sequence)
  from case_record
order by decision_year,group_abbr,decision_number
DECISION_YEAR
GROUP_ABBR
DECISION_NUMBER
SEQUENCE_NUMBER
2012
AA
1
1
2012
AA
2
21
2012
AA
3
22
2012
BB
1
2
2012
BB
2
25
2013
AA
1
38
2013
AA
2
39
2013
AA
3
42
2013
AA
4
43
2013
BB
1
37
2013
BB
2
41
2013
BB
3
45
2013
CC
1
33
2013
CC
2
34
2013
CC
3
36
for retrieval (assuming decision_year,group_abbr,decision_number as being the key):
select decision_year,group_abbr,decision_number -- the rest of columns
  from (select decision_year,
               group_abbr,
-- the rest of columns
               row_number() over (partition by decision_year,group_abbr order by decision_number) decision_number
          from case_record
         where decision_year = :decision_year
           and group_abbr = :group_abbr
where decision_number = :decision_number
DECISION_YEAR
GROUP_ABBR
DECISION_NUMBER
2013
AA
4
if that's acceptable
Regards
Etbin

Similar Messages

  • How can prevent duplication of condition types in sales order??

    How can prevent duplication of condition types in sales order.
    While we want Amount field Changeable by user.
    Please give me solution.

    Dear Rohit,
    Can you explain your scenario in detail with an example or any screen shot so that we will help you in easy way ...
    Regards,
    C.B Reddy

  • How do I create Equal Height Columns with my Background Images?

    Hi there,
    here is my page http://www.allthingsprintuk.co.uk/ATPHome.html
    My problem is that the side bar HTML list is coming off the page in IE. & also the html  in the header can look awful due to browser settings.
    My question is how do I create Equal Height Columns with my Background Images so that they fit with the HTML text? Is there a good link you can point me to, or a tutorial?
    The only way I can see by doing it is slicing my images up into 3 (top middle & bottom) & then setting the middle to repeat y????
    Or does anyone know of a way to create rounded corners WITH drop shadows in CSS that will work on all browsers?
    Thanks in advance
    Louisa

    Try these http://www.pixelan.com/

  • How to display more than one column with for each

    Hi guys,
    how to display more than one column with for each like below?
    for each
    Item1
    Item2
    Item3
    Item4
    Item5
    Item6
    Item7
    Item8
    Item9
    Item10
    End for each
    for each          
    Item1     Item2     Item3
    Item4     Item5     Item6
    Item7     Item8     Item9
    Item10          
    End for each

    Take a look at this to see if the solution provided would work for you: https://blogs.oracle.com/xmlpublisher/entry/multi_column_row_woes
    Won't you have more than 10 records in your data file ? If you are going to have only 10 items then you may be able to use position() function to limit it to 3 each..
    Take a look at this: https://blogs.oracle.com/xmlpublisher/entry/turning_rows_into_columns
    Thanks,
    Bipuser

  • Is it possible to create a Column with Conditional Mandatory with another Column?

    Is it possible to create a Column with Conditional Mandatory with another Column?
    For example
    In a Table we have column A, B, C.
    A is Primary Column.
    B is Optional
    C is Conditional Mandatory.
    A B
    C
    12345 ABC
    OK
    12346 NULL
    NULL
    12347 ABC
    OK
    Only if the B Column has the value then only C column should be mandatory

    I guess you can't create a condtional mandatory column directly. However, you can use check constraint to on the column
    create table YourTable
      A int primary key,
      B char(3),
      C int,
      constraint ch_con check(
                                B
    is not null
    or C is null

  • How to insert data in a column with uniqueidefier data type

    Guys,
    I need insert data in a column with uniqueidefier data type, when i am trying to that getting error.
    error message says: "Conversion failed when converting from a character string to uniqueidentifier."
    I have data in table a col1,col2,col3,col4 - col3,col4 has datatype as varchar and i am updating table b columns col1,col2 with table a col3 and col4.
    Please guide how to do it.

    Hi,
    Not any String can be convert to uniqueidentifier.
    1. you have to make sure u use a value which is fir to be uniqueidentifier
    2. Use convert or cast in the insert query in order to convert the string into uniqueidentifier
    insert X ... convert(uniqueidentifier, 'string which fit to be convert to uniqueidentifier')
    Please post DDL+DML for more specific help
    DDL = Data Definition Language. In our case that is, CREATE TABLE statements for your tables and other definitions that are needed to understand your tables structure and there for let us to test and reproduce the problem in our server. Without DDL no one
    can execute any query.
    How to get DDL: Right click on the table in Object Explorer and select script table as CREATE. Post these create table scripts here.
    DML = data manipulation language is a family of queries used for manipulating the data it self like: inserting, deleting and updating data. In our case we need some sample data in order to check the query and get result, so we need some indert query for
    sample data.
    If you post a "create query" for the tables and "insert query" with some sample, then we could help you without Assuming/Guessing. There is a reason that DDL is generally asked for and expected when discussing query problems - it helps
    to identify issues, clarify terminology and prevent incorrect assumptions.  Sample data also provides a common point of reference for the discussion. A script that can be used to illustrate or reproduce the issue you have, will encourage others to help.
    [Personal Site] [Blog] [Facebook]

  • How to Insert a User Defined Column with CheckBox In ADF Swings

    I have create JTable by dragging a view object from Data Control Palette .But apart from columns listed in JTable i need to insert a User Defined column with Check Box selection option in each row .
    Can any one help me out to sort the problem.
    Regards
    Bhanu Prakash
    Message was edited by:
    user579125

    I retrieve 10 column from Database and build JTable. But apart from 10 column displayed i need to display one more column( User Defined) at run time with the check box option for each row . Because on select of corresponding check box i need to do some mathematical calculation. add also How do i know whether check box is selected or not.
    Regards
    Bhanu Prakash

  • How can I update a Site Column with the content of an array with javascript CSOM?

    I'm relative new to Sharepoint 2013, I'm trying to update the content of a Site column with the content of an array, I can retrieve and visualize the content of my site column, the user is able to change and save the necessary part and the changes are
    saved into an array, now I have to update the content of the site column with the content of the array, but for some kind of reasons I can't accomplish that, any suggestion/example? This is my code so far to retrieve, visualize the site column and store the
    mofication into my array.
        <body>
                <select id="dropdown" name="dropdown" onchange="optSelect()">
                    <option value="EngineType_Cylinders">EngineType_Cylinders</option>
                    <option value="EngineType_EngineCycle">EngineType_EngineCycle</option>
                    <option value="EngineType_EngineFamily">EngineType_EngineFamily</option>
                    <option value="EngineType_Euro">EngineType_Euro</option>
                    <option value="EngineType_FamilyEvolution">EngineType_FamilyEvolution</option>
                    <option value="EngineType_GasEmissionLevel">EngineType_GasEmissionLevel</option>
                    <option value="EngineType_Power">EngineType_Power</option>
                    <option value="EngineType_PowerSupply">EngineType_PowerSupply</option>
                    <option value="EngineType_Use">EngineType_Use</option>
                </select><br />
                <textarea id="textareadisplay" rows="25" cols="23"></textarea><br />
                <input type ="button" value="Update values" onclick="addItemsToColumns()" />
            </body>
    My Javascript
        $(function () {
            SP.SOD.executeOrDelayUntilScriptLoaded(Function.createDelegate(this, function () {
               var select = document.getElementById('dropdown').value;
                console.log(select);
                getSiteColumns(select);
            }), 'SP.js');
        var fieldChoice;
        var choices;
        var addFields = [];
        var slc;
        var clientContext;
        function optSelect() {
            slc = document.getElementById('dropdown').value;
            getSiteColumns(slc);
        function getSiteColumns(selection) {
           clientContext = SP.ClientContext.get_current();
            if (clientContext != undefined && clientContext != null) {
                var web = clientContext.get_web();
                fieldChoice = clientContext.castTo(web.get_availableFields().getByTitle(selection), SP.FieldChoice);
                clientContext.load(this.fieldChoice);
                clientContext.executeQueryAsync(Function.createDelegate(this, this.OnLoadSuccess), Function.createDelegate(this, this.OnLoadFailed));
        function OnLoadSuccess(sender, args) {
            choices = fieldChoice.get_choices();
            var textarea = document.getElementById("textareadisplay");
            textarea.value = choices.join("\n");
        function OnLoadFailed(sender, args) {
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        function addItemsToColumns() {
            clientC = SP.ClientContext.get_current();
            var arrayForUpdate = $('#textareadisplay').val().split('\n');
            fieldChoice.set_item(, arrayForUpdate);
            fieldChoice.update();
            clientContext.executeQueryAsync(function () { }, function () { });
        function OnUpdateSuccess(sender, args) {
            var newchoices = fieldChoice.get_choices();
    My problem is on the function addItemsToColumns() please help! Thanks in advance.

    Let's look at your stylesheet -
    <style type="text/css">
    body {
    background-image: url(assets/images/Business%20Men%20In%20Reception%20Col.2.jpg);
    background-repeat: no-repeat;
    background-color: #003;
    margin-left:auto;
    margin-right:auto;
    position: relative;
    width: 960px;
    It's a good idea not to use spaces or any punctuation in your filenames when working for the web.
    #header {
    margin-left:auto;
    margin-right:auto;
    position: relative;
    width: 960px;
    #heading {
    font-family: Georgia, "Times New Roman", Times, serif;
    font-size: 36px;
    font-style: italic;
    font-variant: normal;
    margin-left:auto;
    margin-right:auto;
    There's no need to specify the default values (font-variant:normal) or to specify auto margins for any block element without an explicitly defined width. And wouldn't it make more sense to put the font style on the body tag, where it will inherit into the rest of the page than to restate it as you have done in the next rule?
    #bodytext {
    font-family: Georgia, "Times New Roman", Times, serif;
    font-size: 18px;
    line-height: 25px;
    font-variant: normal;
    width: 300px;
    #container {
    width: 960px;
    position: relative;
    margin-left:auto;
    margin-right:auto;
    .rightimg {
    float: right;
    margin-left: auto;
    padding-right: 40px;
    #heading #navbar ul li {
    padding: 30px;
    </style>
    Margin-left:auto can't work without knowing what the width of the element is....  Keep your CSS lean and targeted - it will help you to debug your layouts.

  • How to update person or group column with peopleeditor control values

    Hi,
    I have created custom aspx page and added "PeopleEditor" control(can select multiple users)  in that page. Now I am trying to update person or group column with peopleeditor control values.I am not getting any error if I select single user
    in PeopleEditor control but getting error if I select more than one user.
    UpdateItem(listItem, "ListColumnName",
    listItem.ParentList.ParentWeb.EnsureUser(peopleeditorId.CommaSeparatedAccounts));
    Can anybody help me out to resolve the issue?
    Thank you in advance!!!
    AA.

    First get all the users/groups from the PeapleEditor by using PeapleEditor.ResolvedEntities
    foreach (PickerEntity pickerEntity in peopleEditor.ResolvedEntities)
    SPPrincipalType principalType = (SPPrincipalType)Enum.Parse(typeof(SPPrincipalType), pickerEntity.EntityData["PrincipalType"].ToString());
    if (principalType == SPPrincipalType.User || principalType == SPPrincipalType.SecurityGroup)
    string loginName = pickerEntity.Key;
    //your code here
    else if (principalType == SPPrincipalType.SharePointGroup)
    string groupName = pickerEntity.Key;
    //your code here
    Add all the users/groups in an instance of SPFieldUserValueCollection
    and then update your list item.
    SPFieldUserValueCollection users = new SPFieldUserValueCollection();
    users.Add(new SPFieldUserValue(web,user.ID,user.Name));
    item["YourUserColumn"] = users;
    item.Update();

  • UPDATE multiple columns with conditional SET parameters

    I have a procedure that updates multiple columns of a table using the procedure's parameter. Is it possible to have one update statement with conditional SET parameter?
    CREATE TABLE TEMP
    (POL_NUM NUMBER,
    OED DATE,
    TERM NUMBER,
    TRANS_CD CHAR(2));
    INSERT INTO TEMP VALUES (1, '1 AUG 2009', 12, 'NB');
    INSERT INTO TEMP VALUES (2, '4 AUG 2009', 12, 'XL');
    INSERT INTO TEMP VALUES (3, '2 AUG 2009', 12, 'RN');
    COMMIT;
    CREATE OR REPLACE PROCEDURE TMP_PROC (
      pPOL_NUM NUMBER,
      pOED IN DATE,
      pTERM IN NUMBER,
      pTRANS_CD CHAR2)
    AS
    BEGIN
      IF pOED IS NOT NULL THEN
        UPDATE TEMP SET OED = pOED WHERE POL_NUM = pPOL_NUM;
      END IF;
      IF pTERM IS NOT NULL THEN
        UPDATE TEMP SET TERM = pTERM WHERE POL_NUM = pPOL_NUM;
      END IF;
      IF pTRAN_CD IS NOT NULL THEN
        UPDATE TEMP SET TRANS_CD = pTRANS_CD WHERE POL_NUM = pPOL_NUM;
      END IF;
      COMMIT;
    EXCEPTION
      WHEN OTHERS THEN
         NULL;
    END;Is it possible to replace multiple IFs from the code to have only one UPDATE statement with condition that update the column only if the passed parameter is not null? In real scenario I have more than 3 columns and I don't want to write many IF blocks.
    Please help Gurus!!
    Edited by: Kuul13 on Sep 18, 2009 1:26 PM

    Hi,
    You certainly don't want to issue separate UPDATE statements for every column; that will be really inefficent.
    SQL has several ways to implement IF-THEN-ELSE logic. CASE is the most versatile, but NVL will do everything you need for this job. You can use one of those to set a column to itself (and therefore not really update that column) when appropriate.
    For example:
    CREATE OR REPLACE PROCEDURE TMP_PROC (
      pPOL_NUM   IN       NUMBER,
      pOED          IN   DATE,
      pTERM          IN   NUMBER,
      pTRANS_CD  IN       CHAR
    AS
    BEGIN
         UPDATE  temp
         SET     oed      = NVL (poed,       oed)
         ,     term      = NVL (pterm,       term)
         ,     trans_cd = NVL (ptrans_cd, trans_cd)
         WHERE     pol_num      = ppol_num;
      COMMIT;     -- Maybe
    END    tmp_proc;"EXCEPTION WHEN OTHERS THEN NULL" is almost always a bad idea. If there's an error, don't you want to know about it? Shouldn't you at least log a message in a warnings table or something?
    Think careflully about whether or not you want to COMMIT every time you call this procedure.
    Just as it's inefficient to issue a separate UPDATE statement for every column, it's also inefficient to issue a separate UPDATE statement for every row. If efficiency is important, it should be possible to UPDATE several rows in a single UPDATE statement, using NVL (or CASE, or COALESCE, or NULLIF, or NVL2, or ...).
    This was a very well-written question! Thanks for providing the CREATE TABLE and INSERT statements, and such a clear explanation.

  • How to sort multiple t:dataTable columns with Tomahawk?

    Hello, I'm using Tomahawk with MyFaces and I'm trying to sort my table by couple of columns. I have year and month cols and when I sort by year and two years are equal, I want to subsort by the months. I actually tried to create a sort method taking sortColumn and ascending as params, but it didn't get invoked by the app. I also tried to put commandButton as headers which call sort(ActionEvent), but it still didn't get invoked. May anyone show me how could I write a backend for the sorting?
    Thanks in advance!
    Regards,
    Mario

    Yes, there is a comparator. I don't find the problem so much TOmahawk specific, I'm actually trying to solve it without it too. But I found where the problem is - in the <t:column> tag - when sortable attribute is enabled, it doesn't call any external methods, no matter if they are actions or actionListeners.
    So when I removed the sortable attribute, my backend method got called. :)
    Regards,
    Mario

  • How to pass prompt value to columns with formula?

    Hello guys
    I have a situation:
    I have a report with 1 column name 'product' and in this column it has a case statement like 'case when item is ('a','b','c','d') then 'Men' else 'women' end'
    Then I have created a dashboard prompt of the exact same column, and I defined the same case statement in the prompt's column formula as the same.. Then I tested the prompt and it is returning only 2 values 'men', 'women'..
    However, when putting the prompt and report on the same dashboard, the report is not accepting the prompt values..
    Then I set the presentation variable on the prompt and call it 'Product', then in the report I created a filter on 'product' column as equal to presentation variable 'product'--- I tried with and without single quotes.. So the filter itself looks like : case when ...... is equal to / is in @{product}
    However, when I then return back to the dashboard, I am getting the error:
    State: HY000. Code: 388918336. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27005] Unresolved column: "Product". (HY000)
    Could anyone help?
    Thanks

    Hola
    is possible that are you using a BINS agrupation into the Column Formula?
    if you form a CASE statement using a Bins agrupation, in the column Formula, this must be disabled to match statements between columns and DB Prompt
    if you are using a BINS agrupation to form the CASE statement, you have to delete the bins agrupation in the Column but keep the CASE statement
    Regards

  • How do  I duplicate row or column with formulas?

    I've never been a big spreadsheet user but I recall being able to intuitively (the only time ever with a MS product) find a way to duplicate a row or column in Excel so that it would replicate the same formulas as the row/column immediately adjacent to it. Can this be done with Numbers?
    Example: Say I've got a row that has values across with a Sum Total cell and an Average cell calculated with formulas. I'd like to add other rows below so they inherit the same formulas (referencing cells in the new rows). I'm already getting irritated just thinking about having to assign formulas over and over again with each new row.
    I hope I'm just missing something obvious.
    CA

    There is a duplicate command under the Edit Menu item. The short cut is the apple key and "D". However, I have the trial copy and it is grayed out. Meaning it is not working. I have my bought copy arriving next week. Hope this is not grayed out in the bought version. This is a deal breaker. I use this command all the time. They need to fix this right away.

  • How can i get totals in columns with formated searches

    How can i do this with SDK if it isn´t posible since formated searches

    This is not possible with formated searches.
    With SDK, depends on if it is Matrix or Grid, on if it is a system form/your own form. But basically, loop throw the form or datasource, and do the sumatory.
    Regards,
    Ibai Peñ

  • How to prevent iPhone apps to sync with iPad

    I have an iPhone and lot of apps on it. All of them are syncing with iPad, but I want to see only HD apps on iPad. So, can I forbid to install iPhone apps on my iPad?
    Thanks for answer!

    You just click on the iPad while connected to itunes, then click on the apps menu on the iPad in iTunes and you can select deselect which apps are synced. It has a drop down on the apps page to let you sort by date, device type, etc. There is also an option that prevents autosyncing of new apps.
    Glor

Maybe you are looking for

  • Home Sharing - ever going to be fixed?

    I seem to be having progressively more trouble with Home Sharing; for something that should work so simply, it fails much too regularly. My iTunes library is hosted from an always on machine wired directly into the main network router (Draytek Vigor

  • Reverb sound come out from my mac mini

    Hi my mac mini sound output always include sound like reverb/echo . No matter i try phone jack out or usb out to speaker and headphone. its easy to hear the reverb sound when play any sound file(voice over). my mac mini up to date version Please help

  • New to CS 6....how can I create default "print document" letter-size artboard?

    New to CS 6....how can I create  a default "print document" letter-size artboard ?

  • The Case of the Disappearing Disk Space

    Last week when I noticed I only had 5.5 gigs on my hard disk, I decided to start deleting files and programs that I didn't really need anymore. I ended up freeing up about 7 gigs! However, I have since noticed something peculiar... As I use my comput

  • Which profiles of h.264 are supported?

    Does Flash media player support h.264 slices (also known as Flexible Macroblock Ordering (FMO))? Specifically, does it support: a) missing slices (ie if a slice is missing only that part of the frame will be corrupted); b) arbitrary slice ordering (A