Constraining child column to be between values in parent record

I know there's not a declarative constraint to do this, but I am wondering what ideas people have for the best pattern to use.
I have a parent table ALPHA with columns ALPHA_ID, START_DATE and END_DATE.
Then I have a child table BETA with columns BETA_ID, ALPHA_ID and TRAN_DATE.
I would like to constrain that BETA.TRAN_DATE is between ALPHA.START_DATE and ALPHA.END_DATE. I'm reluctant to use a trigger because BETA will have many inserts.
I have considered creating a table ALPHA_DATE with columns ALPHA_ID, START_DATE, END_DATE and TRAN_DATE, with the first three columns as a foreign key to the same columns in ALPHA, and a CHECK constraint that (TRAN_DATE between START_DATE and END_DATE), then letting BETA(ALPHA_ID, TRAN_DATE) be a foreign key to ALPHA_DATE(ALPHA_ID, TRAN_DATE).
Thanks,
Matt

You could duplicate START_DATE and END_DATE into BETA table. Then:
SQL> CREATE TABLE ALPHA(
  2                     ALPHA_ID   NUMBER NOT NULL,
  3                     START_DATE DATE NOT NULL,
  4                     END_DATE   DATE NOT NULL
  5                    )
  6  /
Table created.
SQL> ALTER TABLE ALPHA
  2    ADD CONSTRAINT ALPHA_PK
  3      PRIMARY KEY(
  4                  ALPHA_ID
  5                 )
  6  /
Table altered.
SQL> ALTER TABLE ALPHA
  2    ADD CONSTRAINT ALPHA_UK1
  3      UNIQUE(
  4             ALPHA_ID,
  5             START_DATE,
  6             END_DATE
  7            )
  8  /
Table altered.
SQL> CREATE TABLE BETA(
  2                    BETA_ID    NUMBER NOT NULL,
  3                    ALPHA_ID   NUMBER NOT NULL,
  4                    TRAN_DATE  DATE NOT NULL,
  5                    START_DATE DATE NOT NULL,
  6                    END_DATE   DATE NOT NULL
  7                   )
  8  /
Table created.
SQL> ALTER TABLE BETA
  2    ADD CONSTRAINT BETA_FK1
  3      FOREIGN KEY(
  4                  ALPHA_ID,
  5                  START_DATE,
  6                  END_DATE
  7                 )
  8      REFERENCES ALPHA(
  9                       ALPHA_ID,
10                       START_DATE,
11                       END_DATE
12                      )
13  /
Table altered.
SQL> ALTER TABLE BETA
  2    ADD CONSTRAINT BETA_CK1
  3      CHECK(
  4            TRAN_DATE BETWEEN START_DATE AND END_DATE
  5           )
  6  /
Table altered.
SQL> INSERT
  2    INTO ALPHA
  3    VALUES(
  4           1,
  5           SYSDATE - 10,
  6           SYSDATE - 5
  7          )
  8  /
1 row created.
SQL> INSERT
  2    INTO BETA
  3    VALUES(
  4           1,
  5           1,
  6           SYSDATE - 7,
  7           SYSDATE - 10,
  8           SYSDATE - 5
  9          )
10  /
1 row created.
SQL> INSERT
  2    INTO BETA
  3    VALUES(
  4           1,
  5           1,
  6           SYSDATE - 2,
  7           SYSDATE - 10,
  8           SYSDATE - 5
  9          )
10  /
INSERT
ERROR at line 1:
ORA-02290: check constraint (SCOTT.BETA_CK1) violated
SQL> SY.

Similar Messages

  • Child package cannot read param value from parent ssis package

    Hi all,
    I think I must be crazy !! i have a big problem in my ssis project .
    i have more than 40 package one parent and 39 childs 
    i use configuration method to get variable values from parent to child packages and it work well .. but when i copy my ssis project
    to the production server i face the following problem .. childs package didn't read the variables values from the parent package 
    i revised the configuration many times i can't find any missing !!
    any help please ...
    Thanks,

    Do not copy the packages from the projet to the production server, but you must generate the manifest installation including your configuration, and deploy them.
    Note : not forget to include the configuration.
    To learn more about how to install the package :
    Lesson 1:
    http://msdn.microsoft.com/en-us/library/ms365332(v=sql.105).aspx
    Lesson 2 :
    http://msdn.microsoft.com/en-us/library/ms365329(v=sql.105).aspx
    Lesson 3 :
    http://msdn.microsoft.com/en-us/library/ms365321(v=sql.105).aspx

  • UPDATING child table based on the mods to parent record

    I have a one to many relationship between Table A and Table B.
    I have a field in both of my tables that tracks the status of the record in each table. ie: submitted, inprogress, done.
    When records are created in Table A and B, status is set to SUBMITTED. When the application is being reviewed, the status in parent table is changed to INPROGRESS. As soon as the status in Table A changes to INPROGRESS for the parent record, i also want the status in Table B to change to INPROGRESS for the corresponding child records.
    How can I do this? Triggers is one of the solns, but is there something that i can do with the PROCESS option available on the parent form?
    Any help is very much appreciated.

    Hi,
    Firstly, as Oracle is a relational database, you shouldn't need to have the setting on a child record where it will always be the same as the parent record.
    Secondly, a trigger is probably a better place to make the update, if you need to do this, as this would also handle updates outside of Apex.
    Finally, yes you can create a process to do this if you want. You can create an unconditional process (that is, it runs whenever the page is submitted) and does something like:
    UPDATE TABLEB
    SET STATUS = :P1_STATUS
    WHERE FK_ID = :P1_PK_ID
    AND STATUS <> :P1_STATUSAndy

  • General Query to identify parent columns and child columns in a table

    Does anyone know a general query that can be run to identify the child records associated with the parent column within a single table.....and between other tables?
    Am I correct in assuming the parent column is the 'primary key'?
    Thanks.....I'm a new to oracle...and need some help understanding
    my company's crazy DB structure

    You can use
    User_Constraints
    User_Cons_Columns
    views to identify parent and child table columns
    SELECT * FROM User_Constraints WHERE Constraint_Type = 'R' AND Table_Name = '<TABLENAME>';
    SELECT * FROM User_Cons_columns WHERE Constraint_Name = '<Name from Above query>';
    will give you columns of the parent table (if you use value from constraint_name) and of child table (if you use value from r_constraint_name).
    HTH..

  • Update column data to Upper Case in parent and child table

    Hi ,
    I am facing issue while updating column value to upper case in parent table and child table. How can i do that ?
    when updating parent row:
    ORA-02292: integrity constraint (XXXXXXXXXXXXXX_FK) violated - child record found
    When updatng corresponding child row:
    ORA-02291: integrity constraint (XXXXXXXXXXXXXXXX_FK) violated - parent key not found
    how can i update on both the places ?
    Regards,
    AA

    I am facing issue while updating column value to upper case in parent table and child table. How can i do that ?
    Why do you need to do that?
    That is just ONE of several questions you should answer before you start modifying your data.
    1. What is your 4 digit Oracle version? (result of SELECT * FROM V$VERSION)
    2. If both values are the same case what difference does it make what that case is?hen you don't need to alter your original data.
    3. What is the source of the column values you are using now? If you change your data to upper case it will no longer be identical to the source data.
    4. What is your plan for enforcing future values to be stored in UPPER case? Are you going to use a trigger? Have you written and tested such a trigger to see if it will even work the way you expect?
    5. Why aren't you using a surrogate key instead of a 'business' data item? You have just demonstrated one reason why surrogate keys can be useful: their actual value is NOT important.
    You should reexamine your problem and architecture and consider other alternatives.
    One alternative is to add a new 'surrogate key' column to use as the primary key. Just create a new sequence and use a trigger to populate the new column. Your current plans will require a trigger to perform the case conversion so instead of the just use the trigger to provide the value.
    If the change is being done to facilitate searching you could just add a VIRTUAL column UPPER_MY_COLUMN and index that instead. Then you could search on that new virtual column and the data values would still be identical to the original data source.

  • Sort order column with a between filter

    Hi all,
    [using OBI-EE version 10.1.3.3.1]
    I've got a column 'BLOCK_ROW' which contains values A,B,C....AA,AB,AC...BA,BB...FK,FL
    Alphabetically this orders A,AA,AB.... which is incorrect. The order should be A,B,C...
    To be able to sort correctly we added a column 'ROW_SORT' to our model, which is numeric. This column is set as the 'sort order column' in the repository and makes sure the sorting is done correctly.
    So far, so good...
    Now, I want to be able to use a 'between' filter on this column, e.g. between 'A' and 'C'. Unfortunately this returns A,B,C,AA,AB... while I want it to return A,B,C.
    Is this possible?
    Thanks,
    Elio
    Generated SQL:
    select distinct T91353.BLOCK_ROW as c1,
    T91353.ROW_SORT as c2
    from
    <table_name> T91353
    where ( T91353.BLOCK_ROW between 'A' and 'C' )
    order by c2
    --> Sorting handled based on ROW_SORT, between filter not :(

    That will only do the trick in this particular example. Between 'A' and 'AA' will fail again and only returns A and AA while it should return A..Z and AA.
    Using extra filters is always possible but I'm looking for a more robust solution, which also allows for dashboard 'between' prompts based on this column.
    A workaround I came up with is to add a calculated field which concats an '_' in front of the single 'digit' values. This results in: A,B,_C,.....,AA,AB....FL. This set can be ordered alphabetically and this will work for now.
    In the future, however, it might happen that the order of the letters will completely change. In the datamodel this can be achieved by changing the order of the numbers in ROW_SORT.
    Example dataset:
    BLOCK_ROW | ROW_SORT
    Q | 1
    D | 2
    F | 3
    AA | 4
    A | 5
    The filter 'between D and AA' should then result in D,F,AA.
    Any suggestions?
    Thanks,
    Elio

  • Query on column with comma separated values

    I have a proposed table with unnormalized data like the following:
    ID COLA COLB REFLIST
    21 xxx  zzz  24,25,78,412
    22 xxx  xxx  21
    24 yyy  xxx  912,22
    25 zzz  fff  433,555,22
    .. ...  ...  ...There are 200 million rows. There is maximum of about 10 IDs in the REFLIST, though typically two or three. How could I efficiently query this data on the REFLIST column? e.g. something like:
    SELECT id FROM mytable WHERE :myval in reflistLogically there is a many to many relationship between rows in this table. The REFLIST column contains pointers to ID values elsewhere in the table. The data could be normalized so that the relationship keys are in a separate table (in fact this is the current solution that we want to change).
    ID  REF
    21  24
    21  25
    21  78
    21  412
    22  21
    24  912
    ... ...The comma separated list seems instinctively like a bad idea, however there are various reasons for proposing it. The main reason is because the source for this data has it structured like the REFLIST example. It is an OLTP-like system rather than a data warehouse. The source code (and edit performance) would benefit greatly from not having to maintain the relationship table as the data changes.
    Going back to querying the REFLIST column, the problem seems to be building an approriate index for the data. The ideas proposed so far are:
    <li>Make a materialized view that presents the relationships as normalized (e.g. as in the example with ID, REF columns above), then index the plain column - the various methods of writing the view SQL have been widely posted.
    <li>Use a Oracle Text Index (not something I have ever had call to use before).
    Any other ideas? Its Oracle 10.2, though 11g could be possible.
    Thanks
    Jim

    Something like this ?
    This is test demo on my 11.2.0.1 Windows XP
    SQL> create table test (id number,reflist varchar2(30));
    Table created.
    SQL> insert into test values (21,'24,25,78,412');
    1 row created.
    SQL> insert into test values (22,'21');
    1 row created.
    SQL> insert into test values (24,'912,22');
    1 row created.
    SQL> insert into test values (25,'433,555,22');
    1 row created.
    SQL> select * from test
      2  where
      3  ',' || reflist || ',' like '%,22,%';
            ID REFLIST
            24 912,22
            25 433,555,22
    SQL>Source:http://stackoverflow.com/questions/7212282/is-it-possible-to-query-a-comma-separated-column-for-a-specific-value
    Regards
    Girish Sharma
    Edited by: Girish Sharma on Jul 12, 2012 2:31 PM

  • Different measures use same source column but gives different values in SSAS project

    I've inherited a SSAS project. I'm currentlig gaining knowledge, but do not understand this: There are 4 measures that get data from same source table and column. Example measures:
    [Started]
    [Processing]
    [Processed]
    [Finished]
    All of them gets data from a table (view), and a column "Event_count" with just value 0 in each row. Usage of the measure is "Count of non-empty values".
    Correctly all of these measures gives different values, but I don't understand how since they all go against the same source column. I thougt maybe they were defined in Calculated measures, but nothing there. Where or what else could be affecting this behavior?
    Bonus information (problem): One of the measures is returning blank/empty, which is why started with this research at all.
    Help anyone?
    regards .r

    Hi ,
    I would ask if all the measures are under the same measure group ? It is important to know, since in the dimension usage we are creating relationships between dimensions and measure
    groups .
    Did you try the delete all the calculation's code and leave only the " CALCULATE ; " part ? Do the values change after deploying the slim script ?
    Are all properties the same ? defaults & caching ?
    Regards, David .

  • SSRS Column Chart Design Returning values in a format different from SSRS -SSAS Query Designer

    Hi All,
    I have an SSAS cube Measure Group with Multiple Measures that I am attempting to return on one SSRS report and reflect the 
    values using a ssrs column chart.
    My Measure Group (Patients).
    Measures:
    PatientsOnMeds
    PatientOnRelapse
    PatientsCounseld
    TotalNumberOfPatientsRegisterd
    NewlyRegisteredPatients
    HealthPersonelTrainef
    Demension:
    Time (Year) :filtered to 2012 & 2013
    In my SSRS query designer I have filtered the above Measures with Time Dimesion year 2012 & 2013
    and the data is returned as :
    Year |PatientsOnMeds|PatientOnRelapse|TotalNumberOfPatientsRegisterd|NewlyRegisteredPatients|
    2012 | 700          | 526            |  25                          | 456
    2013 | 245          | 245            |  15                          | 70
    Now the problem is when I return this data on the column Chart it's in messed up mesh
    On the chart Data:
    -Values :Measures
    -Series Group: Dimension
    The report values are returned in multiple columns for each value segmented by year i.e year 2012,Year 2013.
    I want a single column for each Measure (value) for each single year and The chart axis to reflect the measures(values) 
    instead of grouping values according to series group.
    instead the legend returns:
    -Year A -PatientsOnMeds
    -Year A -PatientOnRelapse
    -Year B -PatientsOnMeds
    -Year B -PatientOnRelapse
    I would like the legend to reflect on -Year A,Year B in color code that will be highlighted in the column values.
    Please point me in the right course if you can.Your insights are highly appreciated.Thank you in advance.

    Hi Charlie, 
    Thank you for your kind response. 
    In actual I want the legend to show:
    -2012
    -2013
    And the bottom axis to show:
    PatientsOnMeds
    PatientOnRelapse
    PatientsCounseld
    TotalNumberOfPatientsRegisterd
    NewlyRegisteredPatients
    HealthPersonelTrained
    Indicating in color code for Year 2012 and Year 2013.
    This the challenge that I am struggling with.I hope you understand my scenario.
    It aint easy.

  • How to pass column name as a   values from one page  to another

    hi
    i have created a report(pivot) from a table
    SQL> SELECT * FROM T;
    C1  C2          C3 D                SEQ
    A   AA           2                    1
    A   AB           3                    2
    A   AC           2                    3
    B   AB           5                    4
    B   AC           6                    5
    SQL> SELECT C1
      2  ,NVL(MAX(CASE WHEN C2='AA' THEN C3 END),'') AA
      3  ,NVL(MAX(CASE WHEN C2='AB' THEN C3 END),'') AB
      4  ,NVL(MAX(CASE WHEN C2='AC' THEN C3 END),'') AC
      5  ,SUM(C3) FROM T GROUP BY C1;
    C1          AA         AB         AC    SUM(C3)
    A            2          3          2          7
    B                       5          6         11
    SQL>
    my requirement in Apex is like this(reverse)
    eg-
    when i click on cell values '2' then,it should return
    C1  C2          C3 D                SEQ
    A   AA           2                    1
    {quote}how to pass column name as a  values from one page to another
    for example i have to pass 'c2' as a value to next page{quote}for report pivot you can reffer below link
    Report
    Amu

    thanks for your reply
    i 'm doing what exactly you mention here .
    my problem here is
    i have 15 columns
    i am executing a query based on the values of the column(column name)  in the target page
    1)here i am passing(all) the column values to the next page-but  i want to pass only one column values(column name)
    when i click on any cell of that  column
    OR
    2)i can pass all column name to target page -there(in the target page) i can filter out
    i think option 1 would good if you filter out the unwanted columns
    Regards
    Amul

  • Total column not changed between header & detailed screen

    I have a report with header data contains contracts information and detailed data contains orders, debit credit memo related to the contracts.  I write the report using CL_SALV_TABLE to display  contract value, usage  in full ALV_GRID. When I double click on a contract line, it will go to the second screen to show all orders related to that contract.  The second screen with orders information will be in a screen on a container with all standard function ( Export list to Excel, Word format etc..), sort, total and sub total) and a push button to go back to first screen.
      The report works fine but when I am on the second screen, I total and sub total the amount on that screen in order to check with total value in header record and it total up correctly by currency.
    But when I go back to the first screen, select a different contract record,  double click on the line to get to the order info screen,  all order data display correctly except that the total column still show amount from the previous detailed screen.  If I select the column again and click the total, it will total correctly.   I did refresh the data in the screen before go back to first screen but it does not solve the problem.
    DOES ANYONE HAVE A SIMILAR SYMPTON LIKE THIS? 
    Thanks for your advice.
    On the order detailed screen, I create a container with screen 100 and write PAI, PBO like this:
    Screen 100:
    process before output.
      module status_0100.
      module load_data_to_control.   "Load usage data to screen
    process after input.
    module user_command_0100.
    module status_0100 output.
      set pf-status 'PF100'.
      set titlebar 'T100'.
    endmodule.  
    module load_data_to_control output.
      if gr_cont is not bound.
        create object gr_cont
          exporting
            container_name = 'CONTAINER_100'
          exceptions
            others         = 1.
        if  sy-subrc <> 0.
          message a052(zvn) with
          ' No container object found'.
        endif.
        try.
            cl_salv_table=>factory(
            exporting
         list_display   = list_display
              r_container = gr_cont
          container_name =
            importing
              r_salv_table = gr_alv_2
            changing
              t_table = gt_orders
          catch cx_salv_msg into gr_error.
        endtry.
        perform set_functions.        " Set all standard function in screen 100
        perform set_column_order using gr_alv_2.       "Set column format, display
        perform handle_events.                       "Register events for selection mode & user commands
         Display order screen 0100
        gr_alv_2->display( ).
      else.
        gr_alv_2->refresh( ).
    endif.
    module user_command_0100 input.
      data: wa_d type gt_dtab,
            ls_contract type vbeln,
            ls_order    type vbeln,
            ls_invoice  type vbeln,
            ls_belnr type belnr_d,
            ls_row   type char10.
      data: l_text type char128.
        case  sy-ucomm.
        when 'RETURN' or 'BACK' or 'EXIT' or 'CANCEL'.
    *... refresh the table in order to see the new data
          gr_alv_2->refresh( ).
          leave to screen 0.
        when others.
      endcase.
    endmodule.                 " USER_COMMAND_0100  INPUT

    Hi ,
    When you are using the CL_SALV_TABLE, what is the use of screen 100. Better populate the evnts table in CL_SALV_TABLE
    Cheers
    Pavan

  • How to replace variant to the column name to set value?

    e.g.:i have many columns in my table.now i need to control of the visual attribute.now i hope iterator the columns to set visual value.
    for example:i have a node testNode and a value attribute named testValue of it.i bind it to the some context.
    now i hope used such code to operate it:
    <b>String x="testValue";
    wdContext.currentTestNodeElement.setx(WDVisibility.VISIBLE);</b>
    you know it cann't run.who can give me some advices on it.

    Create a value node called "ColumnVisibility" ( <b>with cardinality 1:1 </b>) under the root context.
    Create as many value attributes ( datatype: ddic:com.sap.ide.webdynpro.uielementdefinitions.Visibility ) as the number of columns in your table and bind them to the visibility property of the appropriate columns.
    (For example: The attributes ColumnOneVisibility, ColumnTwoVisibility, ColumnThreeVisibility are bound to column1, column2, column3).
    Now use this code to control the visibility of columns
    String[] attributeNames = {"ColumnOneVisibility", "ColumnThreeVisibility","ColumnTwoVisibility"};
        for(int k = 0; k < attributeNames.length; k++)
             IWDNodeElement columnVisibilityElement =
    (IWDNodeElement)wdContext.currentColumnVisibilityElement();
             /** Use your condition here */
             /** and set WDVisibility to VISIBLE or NONE depending upon the requirement*/
    columnVisibilityElement.setAttributeValue(attributeNames[k],(WDVisibility) WDVisibility.NONE);
    Bala
    Message was edited by: Bala Krishnan

  • How to put the column name and variable value in the alert message.

    Dear,
    how can i put the column name and variable value in the alert message text. i want to display an alert which tell the user about the empty textboxes. that these textboxes must be filled.
    Regards:
    Muhammad Nadeem
    CHIMERA PVT. LTD.
    LAHORE
    [email protected]

    Hello,
    The name of the item that fires the current trigger is stored in the :SYSTEM.TRIGGER_ITEM system variable.
    The value contained in this item can be retrived with the Name_In() built-in
    value := Name_In( 'SYSTEM.TRIGGER_ITEM') ;
    LC$Msg := 'The item ' || :SYSTEM.TRIGGER_ITEM || ' must be entered' ;
    Set_Alert_Property('my_alert_box', ALERT_MESSAGE_TEXT, LC$Msg ) ;
    Ok := Show_Alert( 'my_alert_box' ) ;
    ...Francois

  • Print out a column value only if another column has a specific value (CASE Statement)

    Hello all,
    I tried many hours to find a solution for the following request but wasn't successful. Maybe you could help me.
    I've using the already existing SQL Views in Microsoft Service Manager to do some basic reporting about my tickets.There is no closed date in the activity tickets so I decided to print out the lastmodified timestamp when the status is "closed".
    That's my query:
    SELECT DISTINCT
    dbo.DisplayStringView.DisplayName AS Status,
    CASE WHEN dbo.DisplayStringView.DisplayName = 'Closed' THEN dbo.DisplayStringView.LastModified ELSE 'NO CLOSED Date' END AS ClosedDate
    FROM dbo.MTV_System$WorkItem$Activity$ManualActivity LEFT OUTER JOIN
    dbo.DisplayStringView ON dbo.MTV_System$WorkItem$Activity$ManualActivity.Status_8895EC8D_2CBF_0D9D_E8EC_524DEFA00014 = dbo.DisplayStringView.LTStringId
    Unfortunatelly I'm not getting the value from dbo.DisplayStringView.LastModified. SQL outputs that it is not possible to convert the string to date/time.
    I think there is a problem with the CASE statement in combination with a value select.
    Any ideas how to print out a column value only if another column has a specific value?

    I think it is the other way if you want the missing date shown as a string.
    CASE
    WHEN
    dbo.DisplayStringView.DisplayName
    =
    'Closed'
    THEN
    Convert( varchar(10),dbo.DisplayStringView.LastModified
    , 101) ELSE
    'NO CLOSED Date'
    END
    AS
    ClosedDate 

  • Difference between value and binding ?

    hello
    I am afraid I am not clear on difference between value and binding of a component?
    I will appreciate if you supply an explanation.
    kind regards

    Binding? Aren't you talking about JSF? That term doesn't occur in JSP world.

Maybe you are looking for

  • How to use excel api in java?

    I need to use excel api in Java to generate data in excel format. Can any one tell any of the use ful Excel api that we can down load from net? i have read about Apache's POi-hssf-Java api. But the jar i downloaaded from Apache site is not working ?

  • Using CreateObject for Webservice with username and password

    When using createObject() to call a web service how do I pass in the user name and password required by the service? If I do a cfdump on the webservice object I see it has setUserName() and setPassword() methods but they don't seem to be working. I a

  • How  to verify yum configuration  in OEL . is there any way  to rollback the package

    Hi , How we can verify  the yum configurtion . is there any way to rollback the package using yum Also  let me know how to rollback packages that upgraded using up2date .

  • Download objects in request (smaller file)

    Hello, I´ve tried a couple of times to download the transport requests in files, because there´s no RFC-connection from the german system to the english system. When I get the file, it contains less bytes than the stated amount in column Length. Exam

  • Slow performance with Seagate External USB Drive

    I have a 250GB Seagate external USB. The external drive is not a pocket drive and it has its own power supply. When I first got the drive (a few months ago) I mounted, paritioned and formatted the drive without any problems. I backed up my Mac HD wit