PRIMARY KEY(MASTER)를 REFERENCE하는 FOREIGN KEY 찾는 SQL

제품 : ORACLE SERVER
작성날짜 : 2004-03-12
PRIMARY KEY(MASTER)를 REFERENCE하는 FOREIGN KEY 찾는 SQL
========================================================
$sqlplus sys/manager(SYS user 로 login 함)
sql> select c.name constraint_name
from dba_objects a,
cdef$ b,
con$ c
where a.object_name = 'TABLE_NAME'
and a.object_id = b.robj#
and b.con# = c.con#
/

Hello again,
May be I was not clear enough.
Scenario 1: We use the master-detail form as is with the default oolbar. In this case, the user can insert the detail records one by one without needing the primary-foreign key value since this is handled by default.
Once we save the form (commit_form), I use the pre-insert trigger to get the master block primary key generated from the sequence and since the detail block key is copied from this value, both are saved correctly and it is the end of the story.
Scenario 2: As explained in the initial post, the user will populate the detail records one by one by clicking on the -INSERT DETAIL- button and hence has a window where he can insert the detail info and then be brought back to the master-detail form every time he enters a new detail record.
The problem here is that I can't generate the primary key for the master block since the client has the following requirement:
The user can always change his mind and not complete, meaning save the form, his process
As such, the key should be generated in the last step before Commit.

Similar Messages

  • PRIMARY KEY PARTITIONED INDEXES 생성방법 (ORA-2429, ORA-1408)

    제품 : ORACLE SERVER
    작성날짜 : 2004-08-13
    PRIMARY KEY PARTITIONED INDEXES 생성방법 (ORA-2429, ORA-1408)
    ============================================================
    PURPOSE
    primary key partitioned indexes 를 생성하는 방법을 알아 봅니다.
    SCOPE
    Oracle Partitioning Option은 8~10g Standard Edition에서는 지원하지
    않는다.
    Example:
    SQL> -- 먼저 partitioned table TEST_A 를 생성합니다.
    SQL>
    SQL> CREATE TABLE test_a (col1 number, col2 number, col3 varchar2(20))
    2 PARTITION BY RANGE (col1, col2)
    3 (partition part_test_a_1 values less than (10, 100),
    4 partition part_test_a_2 values less than (20, 200),
    5 partition part_test_a_3 values less than (30, 300),
    6 partition part_test_a_4 values less than (40, 400));
    Table created.
    SQL> -- partitioned table TEST_B 를 생성합니다.
    SQL>
    SQL> CREATE TABLE test_b (col1 number, col2 number, col3 varchar2(20))
    2 PARTITION BY RANGE (col1, col2)
    3 (partition part_test_b_1 values less than (10, 100),
    4 partition part_test_b_2 values less than (20, 200),
    5 partition part_test_b_3 values less than (30, 300),
    6 partition part_test_b_4 values less than (40, 400));
    Table created.
    SQL> -- TEST_A 테이블에
    SQL> -- non-unique local partitioned index, IX_TEST_A 를 생성합니다.
    SQL>
    SQL> CREATE INDEX ix_test_a ON test_a(col1, col2)
    2 LOCAL
    3 (partition ix_test_a_1,
    4 partition ix_test_a_2,
    5 partition ix_test_a_3,
    6 partition ix_test_a_4);
    Index created.
    SQL> -- TEST_B 테이블에
    SQL> -- unique global partitioned index, IX_TEST_B 를 생성합니다.
    SQL>
    SQL> CREATE UNIQUE INDEX ix_test_b1 ON test_b(col1, col2)
    2 GLOBAL PARTITION BY RANGE (col1, col2)
    3 (partition ix_test_b1_1 values less than (20, 200),
    4 partition ix_test_b1_2 values less than (maxvalue, maxvalue));
    Index created.
    SQL> -- TEST_A 테이블에 rimary key constraint (PK_TEST_A) 를 추가 합니다.
    SQL>
    SQL> ALTER TABLE test_a ADD CONSTRAINT pk_test_a
    2 PRIMARY KEY (col2, col1);
    Table altered.
    SQL> -- index IX_TEST_A 를 drop 하려고 하면 다음 에러가 발생합니다.
    SQL>
    SQL> DROP INDEX ix_test_a;
    drop index ix_test_a
    ERROR at line 1:
    ORA-02429: cannot drop index used for enforcement of unique/primary key
    SQL> -- TEST_B 테이블에 partition IX_TEST_B1 에서 사용된 같은 columns 들을 사용해서
    SQL> -- 새로운 두번째 index (IX_TEST_B2) 를 생성하려고 하면
    SQL> -- 다음 에러가 발생합니다.
    SQL>
    SQL> CREATE INDEX ix_test_b2 ON test_b(col1, col2)
    2 LOCAL;
    create index ix_test_b2 on test_b(col1, col2)
    ERROR at line 1:
    ORA-01408: such column list already indexed
    SQL> -- TEST_B 테이블에 primary key constraint (PK_TEST_B) 를 추가 합니다.
    SQL>
    SQL> ALTER TABLE test_b ADD CONSTRAINT pk_test_b
    2 PRIMARY KEY (col1, col2);
    Table altered.
    SQL> -- index IX_TEST_B1 를 drop 하려고 하면 다음 에러가 발생합니다.
    SQL>
    SQL> DROP INDEX ix_test_b1;
    drop index ix_test_b1
    ERROR at line 1:
    ORA-02429: cannot drop index used for enforcement of unique/primary key
    SQL> -- indexes 들과 각 indexes 이 걸려있는 tables 의 목록입니다.
    SQL>
    SQL> SELECT index_name, partition_name, status
    2 FROM user_ind_partitions
    3 ORDER BY index_name, partition_name;
    INDEX_NAME PARTITION_NAME STATUS
    IX_TEST_A IX_TEST_A_1 USABLE
    IX_TEST_A IX_TEST_A_2 USABLE
    IX_TEST_A IX_TEST_A_3 USABLE
    IX_TEST_A IX_TEST_A_4 USABLE
    IX_TEST_B1 IX_TEST_B1_1 USABLE
    IX_TEST_B1 IX_TEST_B1_2 USABLE
    6 rows selected.
    SQL> -- TEST_A 테이블에서 primary key constraint 를 drop 합니다.
    SQL>
    SQL> ALTER TABLE test_a DROP CONSTRAINT pk_test_a;
    Table altered.
    SQL> -- TEST_B 테이블에서 primary key constraint 를 drop 합니다.
    SQL>
    SQL> ALTER TABLE test_b DROP CONSTRAINT pk_test_b;
    Table altered.
    SQL> -- indexes 들과 각 indexes 이 걸려있는 tables 의 목록을 다시 봅니다.
    SQL> -- 여기서 주의해서 보아야 할 것은 non-unique local partitioned index (IX_TEST_A)
    SQL> -- 은 drop 되지 않고 USABLE 상태로 남아 있다는 것입니다.
    SQL> -- 이렇게 되는 이유는 index (IX_TEST_A) 가 non-unique 이기 때문입니다.
    SQL> -- 반면 unique global partitioned index (IX_TEST_B) 은 drop 되었습니다.
    SQL>
    SQL> SELECT index_name, partition_name, status
    2 FROM user_ind_partitions
    3 ORDER BY index_name, partition_name;
    INDEX_NAME PARTITION_NAME STATUS
    IX_TEST_A IX_TEST_A_1 USABLE
    IX_TEST_A IX_TEST_A_2 USABLE
    IX_TEST_A IX_TEST_A_3 USABLE
    IX_TEST_A IX_TEST_A_4 USABLE
    만일 index 가 primary key 에 정의되어 있는 columns 들과 같은 columns
    을 사용해서 만들어 졌다면 primary key 는 그 underlying index 를 사용합니다.
    이것은 index 가 unique 이건 non-unique 이건 또는 global 이건 local partioned index
    이건 관계없이 적용됩니다.
    위의 예제에서 primary key 가 non-unique index 위에 생성되었다는 것을
    주의해 보시기 바랍니다. 이렇게 되는 이유는 index 안의 값들이 사실
    모두 unique 하기 때문입니다. 그렇지 않을 경우 다음 에러가 발생하게 됩니다.
    "ORA-02437: cannot enable (STEELY.PK_TEST_B) - primary key violated."
    2개의 indexes 가 같은 순서의 같은 columns 을 사용해서 만들어 질 수는 없습니다.
    위의 예제에서 TEST_B 테이블에 두번째 index (IX_TEST_B2) 를 만들려고
    했을때 다음에러가 발생하는것을 확인할 수 있었습니다.
    "ORA-01408: such column list already indexed."
    하지만 columns 들의 순서를 바꾼다면 같은 columns 들을 사용하더라도
    추가적으로 indexes 를 생성할 수 있습니다.
    index (IX_TEST_A) 와 primary key (PK_TEST_A) 에 정의된 column 순서는
    반대로 되어 있습니다. 그러나 primary key 는 IX_TEST_A 를 underlying index
    로 사용하고 있습니다.
    테이블에서 primary key constraint 가 drop 되었을때
    만일 index 가 UNIQUE index 로 생성되었다면 대응하는 index 또한 drop 됩니다.
    이 현상은 LOCAL 또는 GLOBAL partitioned indexes 모두에 적용됩니다.
    partitioning 을 최대한 활용하기 위해서는 partitioned tables/indexes
    를 생성할 때에 STORAGE clause 를 반드시 사용해야 합니다.
    Reference Documents
    <Note:74224.1>

    First, thanks for posting the code that lets us reproduce your test. That is essential for issues like this.
    Because the primary key is global you will not be able to use
    INCLUDING INDEXES
    WITH VALIDATION;And you will need to add the primary key to the temp table
    ALTER TABLE DEMO_INTERVAL_DATA_LOAD_Y ADD CONSTRAINT IDX_DEMO_ROLL_Y PRIMARY KEY (ROLL_NUM);The the exchange will work. You will need to rebuild the primary key after the exchange.

  • Access path difference between Primary Key and Unique Index

    Hi All,
    Is there any specific way the oracle optimizer treats Primary key and Unique index differently?
    Oracle Version
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0      Production
    TNS for IBM/AIX RISC System/6000: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - Production
    SQL> Sample test data for Normal Index
    SQL> create table t_test_tab(col1 number, col2 number, col3 varchar2(12));
    Table created.
    SQL> create sequence seq_t_test_tab start with 1 increment by 1 ;
    Sequence created.
    SQL>  insert into t_test_tab select seq_t_test_tab.nextval, round(dbms_random.value(1,999)) , 'B'||round(dbms_random.value(1,50))||'A' from dual connect by level < 100000;
    99999 rows created.
    SQL> commit;
    Commit complete.
    SQL> exec dbms_stats.gather_table_stats(USER_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1565504962
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6915  consistent gets
            259  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> create index idx_t_test_tab on t_test_tab(col1);
    Index created.
    SQL> exec dbms_stats.gather_table_stats('USER_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1565504962
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6915  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> Sample test data when using Primary Key
    SQL> create table t_test_tab1(col1 number, col2 number, col3 varchar2(12));
    Table created.
    SQL> create sequence seq_t_test_tab1 start with 1 increment by 1 ;
    Sequence created.
    SQL> insert into t_test_tab1 select seq_t_test_tab1.nextval, round(dbms_random.value(1,999)) , 'B'||round(dbms_random.value(1,50))||'A' from dual connect by level < 100000;
    99999 rows created.
    SQL> commit;
    Commit complete.
    SQL> exec dbms_stats.gather_table_stats('USER_OWNER','T_TEST_TAB1',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab1;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1727568366
    | Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |             | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB1 | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6915  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> alter table t_test_tab1 add constraint pk_t_test_tab1 primary key (col1);
    Table altered.
    SQL> exec dbms_stats.gather_table_stats('USER_OWNER','T_TEST_TAB1',cascade => true);
    PL/SQL procedure successfully completed.
    SQL> select col1 from t_test_tab1;
    99999 rows selected.
    Execution Plan
    Plan hash value: 2995826579
    | Id  | Operation            | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                | 99999 |   488K|    59   (2)| 00:00:01 |
    |   1 |  INDEX FAST FULL SCAN| PK_T_TEST_TAB1 | 99999 |   488K|    59   (2)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6867  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL> If you see here the even though statistics were gathered,
         * In the 1st table T_TEST_TAB, the table is still using FULL table access after creation of index.
         * And in the 2nd table T_TEST_TAB1, table is using PRIMARY KEY as expected.
    Any comments ??
    Regards,
    BPat

    Thanks.
    Yes, ignored the NOT NULL part.Did a test and now it is working as expected
    SQL>  create table t_test_tab(col1 number not null, col2 number, col3 varchar2(12));
    Table created.
    SQL>
    create sequence seq_t_test_tab start with 1 increment by 1 ;SQL>
    Sequence created.
    SQL> insert into t_test_tab select seq_t_test_tab.nextval, round(dbms_random.value(1,999)) , 'B'||round(dbms_random.value(1,50))||'A' from dual connect by level < 100000;
    99999 rows created.
    SQL> commit;
    Commit complete.
    SQL>  exec dbms_stats.gather_table_stats('GREP_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL>  set autotrace traceonly
    SQL>  select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 1565504962
    | Id  | Operation         | Name       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |            | 99999 |   488K|    74   (3)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| T_TEST_TAB | 99999 |   488K|    74   (3)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6912  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL>  create index idx_t_test_tab on t_test_tab(col1);
    Index created.
    SQL>  exec dbms_stats.gather_table_stats('GREP_OWNER','T_TEST_TAB',cascade => true);
    PL/SQL procedure successfully completed.
    SQL>  select col1 from t_test_tab;
    99999 rows selected.
    Execution Plan
    Plan hash value: 4115006285
    | Id  | Operation            | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                | 99999 |   488K|    63   (2)| 00:00:01 |
    |   1 |  INDEX FAST FULL SCAN| IDX_T_TEST_TAB | 99999 |   488K|    63   (2)| 00:00:01 |
    Statistics
              1  recursive calls
              0  db block gets
           6881  consistent gets
              0  physical reads
              0  redo size
        1829388  bytes sent via SQL*Net to client
          73850  bytes received via SQL*Net from client
           6668  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
          99999  rows processed
    SQL>

  • IOTs and primary keys

    hi,
    I am reading chapter 10 of expert oracle database architecture by tom kyte, and I am getting a little confused. It seems to me as if he is saying that an IOT should be built using the PK of that table. What if our table does not have a PK?
    thanks

    OracleGuy777 wrote:
    hi,
    I am reading chapter 10 of expert oracle database architecture by tom kyte, and I am getting a little confused. It seems to me as if he is saying that an IOT should be built using the PK of that table. What if our table does not have a PK? Then you can not create an IOT. It's a rule. http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/schema.htm#i23877
    One of the suggestions is 'try it'. So let us do exactly that - create 2 nearly idetical IOTs - one with and the second without a primary key
    SQL*Plus: Release 10.2.0.1.0 - Production on Sun Nov 1 11:07:37 2009
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Connected to:
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Production
    SQL> CREATE TABLE countries_demo
      2      ( country_id      CHAR(2)
      3        CONSTRAINT country_id_nn_demo NOT NULL
      4      , country_name    VARCHAR2(40)
      5      , currency_name   VARCHAR2(25)
      6      , currency_symbol VARCHAR2(3)
      7      , region          VARCHAR2(15)
      8      , CONSTRAINT    country_c_id_pk_demo
      9                      PRIMARY KEY (country_id ) )
    10      ORGANIZATION INDEX
    11  /
    Table created.
    SQL> edit
    Wrote file afiedt.buf
      1  CREATE TABLE countries_demo2
      2      ( country_id      CHAR(2)
      3        CONSTRAINT country_id_nn_demo NOT NULL
      4      , country_name    VARCHAR2(40)
      5      , currency_name   VARCHAR2(25)
      6      , currency_symbol VARCHAR2(3)
      7      , region          VARCHAR2(15) )
      8*     ORGANIZATION INDEX
    SQL> /
        ORGANIZATION INDEX
    ERROR at line 8:
    ORA-25175: no PRIMARY KEY constraint found
    SQL>SO the conclusion is, whether it makes sense to us or not, we can not create a table without defining a primary key.
    It makes sense to me, since the IOT is actually stored as a unique index with nulls not allowed - for which a PK is a perfect fit. Note that a PK COULD be defined with multiple columns instead of the traditional single column (and often wrong surrogate key)

  • VLD-0201:Table has more than one primary key

    hi
    i'm working with OWB 9.2,I was imported the table from database,when i validating that it is giving message:
    VLD-0201:Table has more than one primary key
    vld-0209:Duplicate unique key i.e:cust_acc and SYS_C00435 detected.
    Can i use this table and generate the mapping with out any errors?
    Any help will be very generate.

    Hi Ashok,
    I'm quite curious how you managed to get a table with 2 PK's.
    I tried it myself:
    =======================================================
    SQL>create table x(c1 number constraint pk1 primary key,c2 number constraint pk2 primary key, c3 date);
    create table x(c1 number constraint pk1 primary key,c2 number constraint pk2 primary key, c3 date)
    ERROR at line 1:
    ORA-02260: table can have only one primary key
    SQL>ed
    Wrote file afiedt.buf
    1* create table x(c1 number constraint uk1 unique,c2 number constraint uk2 unique, c3 date)
    SQL>/
    Table created.
    =====================================================
    As you can see, trying to create a table with more than 1 PK is impossible. With Unique Key, that IS possible (see second example).
    I don't expect mappings to function properly with such an error message.
    Is it possible for you to drop the table in the database, correct the definition of the table in OWB and then deploy that corrected version to the database?
    If on the other hand the table on the database is correct (i.e. has only one PK) then the import into OWB obviously did not go well and I'd suggest you drop the imported definition and try to import it again.
    Cheers, Patrick

  • PRIMARY KEY-FOREIGN KEY 관계 찾기(MASTER TABLE CONSTRAINT 정보 찾는 SQL)

    제품 : ORACLE SERVER
    작성날짜 : 2003-06-19
    PRIMARY KEY-FOREIGN KEY 관계 찾기
    =================================
    PURPOSE
    이 자료는 MASTER TABLE CONSTRAINT 정보를 찾는 SQL이다.
    Explanation
    SCOTT의 EMP table의 Foreign Key와 부모 제약 조건을 찾으려면
    다음의 질의문을 사용하여 찾을 수 있다.
    SQL> alter table dept add constraint dept_pk primary key (deptno);
    Table altered.
    SQL> alter table emp add constraint emp_dept_fk foreign key(deptno)
    references dept(deptno);
    Table altered.
    SQL> select c.constraint_name as "foreign key",
    p.constraint_name as "referenced key",
    p.constraint_type,
    p.owner,
    p.table_name
    from dba_constraints c, dba_constraints p
    where c.owner = 'SCOTT'
    and c.table_name = 'EMP'
    and c.constraint_type = 'R'
    and c.r_owner = p.owner
    and c.r_constraint_name = p.constraint_name;
    foreign key referenced key C OWNER TABLE_NAME
    EMP_DEPT_FK DEPT_PK P SCOTT DEPT
    Example
    none
    Reference Documents
    <Note:1010844.6>

    I don't have intimate knowledge of SQL Server, but to me, your code seems reasonable. I guess there is some "fine point" (a bug?) to using self referenceing foreign keys in SQL Server. It doesn't seem plausible that the error originates with the driver, unless it's a very intelligent kind of driver.
    A "Gordian Knot" kind of solution to your problem is to ask whether you really need the foreign key constraint in the db schema. Is the table used by something other than your EJB? Anyway, putting logic responsible for the correct functioning of your EJB into the db schema is often a bad practice, as it makes the code harder to understand, maintain, port etc.

  • Dynamic SQL Joining between tables and Primary keys being configured within master tables

    Team , Thanks for your help in advance !
    I'm looking out to code a dynamic SQL which should refer Master tables for table names and Primary keys and then Join for insertion into target tables .
    EG:
    INSERT INTO HUB.dbo.lp_order
    SELECT *
    FROM del.dbo.lp_order t1
    where not exists ( select *
    from hub.dbo.lp_order tw
    where t1.order_id = t2.order_id )
    SET @rows = @@ROWCOUNT
    PRINT 'Table: lp_order; Inserted Records: '+ Cast(@rows AS VARCHAR)
    -- Please note Databse names are going to remain the same but table names and join conditions on keys
    -- should vary for each table(s) being configured in master tables
    Sample of Master configuration tables with table info and PK Info :
    Table Info         
    Table_info_ID    Table_Name    
    1        lp_order    
    7        lp__transition_record    
    Table_PK_Info        
    Table_PK_Info_ID    Table_info_ID    PK_Column_Name
    2                1    order_id
    8                7    transition_record_id
    There can be more than one join condition for each table
    Thanks you !
    Rajkumar Yelugu

    Hi Rajkumar,
    It is glad to hear that you figured the question out by yourself.
    There's a flaw with your while loop in your sample code, just in case you hadn't noticed that, please see below.
    --In this case, it goes to infinite loop
    DECLARE @T TABLE(ID INT)
    INSERT INTO @T VALUES(1),(3),(2)
    DECLARE @ID INT
    SELECT @ID = MIN(ID) FROM @T
    WHILE @ID IS NOT NULL
    PRINT @ID
    SELECT @ID =ID FROM @T WHERE ID > @ID
    So a cursor would be the appropriate option in your case, please reference below.
    DECLARE @Table_Info TABLE
    Table_info_ID INT,
    Table_Name VARCHAR(99)
    INSERT INTO @Table_Info VALUES(1,'lp_order'),(7,'lp__transition_record');
    DECLARE @Table_PK_Info TABLE
    Table_PK_Info_ID INT,
    Table_info_ID INT,
    PK_Column_Name VARCHAR(99)
    INSERT INTO @Table_PK_Info VALUES(2,1,'order_id'),(8,7,'transition_record_id'),(3,1,'order_id2')
    DECLARE @SQL NVarchar(MAX),
    @ID INT,
    @Table_Name VARCHAR(20),
    @whereCondition VARCHAR(99)
    DECLARE cur_Tabel_Info CURSOR
    FOR SELECT Table_info_ID,Table_Name FROM @Table_Info
    OPEN cur_Tabel_Info
    FETCH NEXT FROM cur_Tabel_Info
    INTO @ID, @Table_Name
    WHILE @@FETCH_STATUS = 0
    BEGIN
    SELECT @whereCondition =ISNULL(@whereCondition+' AND ','') +'t1.'+PK_Column_Name+'='+'t2.'+PK_Column_Name FROM @Table_PK_Info WHERE Table_info_ID=@ID
    SET @SQL = 'INSERT INTO hub.dbo.'+@Table_Name+'
    SELECT * FROM del.dbo.'+@Table_Name+' AS T1
    WHERE NOT EXISTS (
    SELECT *
    FROM hub.dbo.'+@Table_Name+' AS T2
    WHERE '+@whereCondition+')'
    SELECT @SQL
    --EXEC(@SQL)
    SET @whereCondition = NULL
    FETCH NEXT FROM cur_Tabel_Info
    INTO @ID, @Table_Name
    END
    Supposing you had noticed and fixed the flaw, your answer sharing is always welcome.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Problem with foreign and primary keys migration from SQL Server to Oracle

    Hi folks, i'm using SQL Developer to migrate from a SQL Server database to Oracle and i'm stuck with a couple issues:
    The worst of them so far is the fact that i can't migrate any of the PKs and FKs. After successfully capturing the SQL Server DB model and converting it to Oracle, when the tool generates the scripts, all ALTER TABLE queries that add the PKs and FKs have their target columns duplicated.
    for example: when i'm trying to migrate a simple table that contains an Id (PK) and Name columns, the tool generates the following scripts:
    PROMPT Creating Table TestTable...
    CREATE TABLE TestTable (
    Id NUMBER(10,0) NOT NULL,
    Name VARCHAR2 NOT NULL
    PROMPT Creating Primary Key Constraint PK_TestTable on table TestTable ...
    ALTER TABLE TestTable
    ADD CONSTRAINT PK_TestTable PRIMARY KEY
    Id,
    Id
    ENABLE
    As for the FKs, the tool duplicates the columns as well:
    ALTER TABLE SomeTable
    ADD CONSTRAINT FK_SomeTable_SomeTable2 FOREIGN KEY
    SomeTable2Id,
    SomeTable2Id
    REFERENCES SomeTable2
    Id,
    Id
    ENABLE
    Does anyone have a clue on how to solve these issues? I'd be greatly thankful for any answers!

    Hi Fernando,
    I was unable to replicate this issue. My primary / foreign keys where defined using unique columns.
    PROMPT Creating Primary Key Constraint PK_Suppliers on table Suppliers ...
    ALTER TABLE Suppliers
    ADD CONSTRAINT PK_Suppliers PRIMARY KEY
    SupplierID
    ENABLE
    I tried a few things like
    capturing twice and renaming both models the same
    renaming the converted models
    but with no luck.
    I think this issue is occuring either at the capture or convert phase.
    1) Are you performing the capture online or offline?
    2) Can you provide a the entire DDL for one of these tables and its indexes to see if I can replicate?
    3) Did the capture or convert fail or have to be redone at any stage ?
    I all else fails I would attempt a capture and convert again using a brand new repository (create a new schema in Oracle and associate the migration repository with it).
    Regards,
    Dermot
    SQL Developer Team
    Edited by: Dermot ONeill on Oct 22, 2009 12:18 PM

  • Two foreign keys reference on primary key

    There are two tables:
    1) table CALENDAR with primary key: cal_id
    2) table FACTS with some columns, two of them are dates: cal_id_start_process, cal_id_stop_process
    we want on physical layer create two foreign keys for cal_id_start_process and cal_id_stop_process columns reference on CALENDAR.cal_id
    When we create foreign key for cal_id_start_process: we choose this column and choose CALENDAR table and its primary key. But when we want to create foreign key for cal_id_stop_process - we cannot coose table CALENDAR again.
    Is this rigth, that only one column from table can reference on specified primary key in CALENDAR table?
    How to create two foreign key on one table primary key?

    More complex. In your example there'll be such SQL:
    select c.cal_id, f.cal_id_start, f.cal_id_stop
    from CALENDAR c, FACTS f
    where c.cal_id = f.cal_id_start and c.cal_id = f.cal_id_stop
    (It meens FACTS.cal_id_start = FACTS.cal_id_stop )
    In my case, I want for such join:
    select c1.cal_id, c2.cal_id, f.cal_id_start, f.cal_id_stop
    from CALENDAR c1, CALENDAR c2, FACTS f
    where c1.cal_id = f.cal_id_start and c2.cal_id = f.cal_id_stop
    Edited by: annylut on Dec 22, 2011 3:33 PM

  • TIPS(9):PARENT-CHILD(FOREIGN KEY) 관계를 갖는 MASTER TABLE의 PRIMARY KEY 확인.

    제품 : SQL*PLUS
    작성날짜 : 1996-10-21
    TIPS(9) : PARENT-CHILD관계를 갖는 TABLE의
    PRIMARY key, FOREIGN key의 COLUMN 명과 POSITION 확인
    ==============================================================
    ** Name : Show_Position.Sql
    ** Usage : @Show_Positions Parent_Table Child_Table
    ** Description : Shows Primary And Foreign Key Positions
    ** WARNING : 이 문장은 해당 Table의 Constraint생성시 Naming
    ** Convention을 따른 경우에 적용되도록 되어 있다.
    SET VERIFY OFF
    CLEAR BREAK
    BREAK ON CONSTRAINT_NAME ON TABLES
    SELECT SUBSTR(CONSTRAINT_NAME,1,27) CONSTRAINT_NAME,
    SUBSTR(TABLE_NAME,1,15) TABLES,
    SUBSTR(COLUMN_NAME,1,15) COL_NAME,
    SUBSTR(POSITION,1,3) POSITION,
    SUBSTR(OWNER,1,7) OWNER
    FROM USER_CONS_COLUMNS
    WHERE TABLE_NAME = UPPER('&1')
    AND CONSTRAINT_NAME LIKE 'PK%'
    UNION
    SELECT SUBSTR(CONSTRAINT_NAME,1,27) CONSTRAINT_NAME,
    SUBSTR(TABLE_NAME,1,15) TABLES,
    SUBSTR(COLUMN_NAME,1,25) COL_NAME,
    SUBSTR(POSITION,1,3) POSITION,
    SUBSTR(OWNER,1,7) OWNER
    FROM USER_CONS_COLUMNS
    WHERE TABLE_NAME = UPPER('&2')
    AND CONSTRAINT_NAME LIKE 'FK%'
    ORDER BY 1 DESC , 4 ASC;
    < 실행 예 >
    SQL> @SHOW_POSITIONS EMP_SERVICE EMP_SERVICE_LOG
    CONSTRAINT_NAME TABLES COL_NAME POS
    PK_EMP_SERVICE EMP_SERVICE EMP_ID 1
    CUST_ID 2
    FK_EMP_SERVICE_LOG_EC EMP_SERVICE_LOG EMP_ID 1
    CUST_ID 2

    제품 : SQL*PLUS
    작성날짜 : 1996-10-21
    TIPS(9) : PARENT-CHILD관계를 갖는 TABLE의
    PRIMARY key, FOREIGN key의 COLUMN 명과 POSITION 확인
    ==============================================================
    ** Name : Show_Position.Sql
    ** Usage : @Show_Positions Parent_Table Child_Table
    ** Description : Shows Primary And Foreign Key Positions
    ** WARNING : 이 문장은 해당 Table의 Constraint생성시 Naming
    ** Convention을 따른 경우에 적용되도록 되어 있다.
    SET VERIFY OFF
    CLEAR BREAK
    BREAK ON CONSTRAINT_NAME ON TABLES
    SELECT SUBSTR(CONSTRAINT_NAME,1,27) CONSTRAINT_NAME,
    SUBSTR(TABLE_NAME,1,15) TABLES,
    SUBSTR(COLUMN_NAME,1,15) COL_NAME,
    SUBSTR(POSITION,1,3) POSITION,
    SUBSTR(OWNER,1,7) OWNER
    FROM USER_CONS_COLUMNS
    WHERE TABLE_NAME = UPPER('&1')
    AND CONSTRAINT_NAME LIKE 'PK%'
    UNION
    SELECT SUBSTR(CONSTRAINT_NAME,1,27) CONSTRAINT_NAME,
    SUBSTR(TABLE_NAME,1,15) TABLES,
    SUBSTR(COLUMN_NAME,1,25) COL_NAME,
    SUBSTR(POSITION,1,3) POSITION,
    SUBSTR(OWNER,1,7) OWNER
    FROM USER_CONS_COLUMNS
    WHERE TABLE_NAME = UPPER('&2')
    AND CONSTRAINT_NAME LIKE 'FK%'
    ORDER BY 1 DESC , 4 ASC;
    < 실행 예 >
    SQL> @SHOW_POSITIONS EMP_SERVICE EMP_SERVICE_LOG
    CONSTRAINT_NAME TABLES COL_NAME POS
    PK_EMP_SERVICE EMP_SERVICE EMP_ID 1
    CUST_ID 2
    FK_EMP_SERVICE_LOG_EC EMP_SERVICE_LOG EMP_ID 1
    CUST_ID 2

  • Master Detail Forms with 2 composite primary keys - Is there a workaround?

    Hello All,
    I have been searching for a workaround to the maximum 2 part primary key restriction on the multi-row updates, and master-detail forms, and am hoping that someone can help me. I am using HTMLDB v2.0.0.00.49 with IE 6 against a 9.2 DB.
    I successfully implemented the workaround of Fred Stoopendaal's (see Updata PK on HTML DB ) and it works fine for single page multi-record updateable forms, but alas I haven't been able to extend it to master detail forms (I think it is something to do with Oracle not allowing the "returning" clause on views).
    Here is what I tried:
    two tables, one with a 2 part composite primary key, which is the master table, and a detail table with 3 part composite primary key -
    --------- BEGIN SQL ---------
    create table master_table
    ( master_col1 number
    , master_col2 number
    , master_col3 varchar2(30)
    , constraint master_pk primary key (master_col1,master_col2));
    create table detail_table
    (detail_col1 number
    ,detail_col2 number
    ,detail_col3 number
    ,detail_col4 varchar2(30)
    , constraint detail_pk primary key(detail_col1,detail_col2,detail_col3)
    , constraint master_detail_fk foreign key (detail_col1,detail_col2) references master_table(master_col1,master_col2));
    create or replace view v_master_table as
    select rowid mata_rowid,mata.*
    from master_table mata;
    create or replace view v_detail_table as
    select rowid deta_rowid,
    (select rowid from master_table mata where mata.master_col1 = deta.detail_col1 and mata.master_col2 = deta.detail_col2) deta_mata_rowid
    , deta.*
    from detail_table deta;
    create or replace trigger mata_ins_upd_trg
    instead of insert or update on v_master_table
    referencing new as new old as old
    for each row
    begin
    if inserting then
    insert into master_table (master_col1, master_col2, master_col3)
    values (:new.master_col1, :new.master_col2, :new.master_col3);
    end if;
    if updating then
    update master_table
    set master_col1 = :new.master_col1,
    master_col2 = :new.master_col2,
    master_col3 = :new.master_col3
    where rowid = :old.mata_rowid;
    end if;
    end;
    create or replace trigger deta_ins_upd_trg
    instead of insert or update on v_detail_table
    referencing new as new old as old
    for each row
    begin
    if inserting then
    insert into detail_table ( detail_col1, detail_col2, detail_col3, detail_col4)
    values (:new.detail_col1, :new.detail_col2, :new.detail_col3, :new.detail_col4);
    end if;
    if updating then
    update detail_table
    set detail_col1 = :new.detail_col1,
    detail_col2 = :new.detail_col2,
    detail_col3 = :new.detail_col3,
    detail_col4 = :new.detail_col4
    where rowid = :old.deta_rowid;
    end if;
    end;
    --------- END SQL ---------
    Then I created a master-detail form in Apex on the two views, using the mata_rowid and deta_rowid as primary keys, and mata_rowid=deta_mata_rowid as the link. I realise that using a function to fetch the master rowid within the detail view query is costly, but it was my intention to modify the record fetch queries to use the real FK columns once things were up and running.
    It seems to generate the pages ok, and I can insert/update master table records, but as soon as I modify records in the detail table things go a bit haywire. I can't find any documentation on how the inbuilt MRU/MRD logic works, so can't figure out the issue.
    Can anyone out there tell me what the problem is with the logic above, or if they have come up with a neat solution to this annoying limitation. I know that many will say that I should modify the data model to use surrogate primary keys, but many of the uses for HTMLDB are new interfaces for old schemas, so a workaround that doesn't involve wholesale data model changes would be preferable.
    Thanks in advance,
    Mike Cretan

    Hi, this is likely not the most elegant way...but perhaps the simplest -- and I didn't have much time to play.
    I used Wizard to create two separate Master Detail forms, each with a separate detail table. Thus I ended up with four pages:
    Page "A" - "Selector" page for Master (Report), with Edit link driving to Detail-1
    Page "B" - Editable Master/Detail-1 page (HTML / Report)
    Page "C" - "Selector" page for Master (Report), with Edit link driving to Detail-2
    Page "D" - Editable Master/Detail-2 page (HTML / Report)
    Then I selected the primary key column TWICE on the Report on Page A. Modified the second instance of this column to navigate to Page D (passing primary key) exactly the way the original instance of this column navigates to Page B. Then I deleted Page C.
    Since you can have only one Tabular Entry form per page, this seemed the best way to drive two separate detail tables from a common interface.

  • Foreign key constraint on multi-column primary key accepts 1 empty column!?

    Hi, we have a reference table with a two-column primary key. In the child table there is a non-mandatory foreign key constraint to this table. So if both child columns are null it's ok too. But now we see that if one of the two child table columns that build up the foreign key is null, the other column can have any (non-existant in the master-tabel) value you like!? That does not make sense.
    Can anyone explain this to me???
    Regards, Paul.

    Paul, I believe that this is in accordance to the ANSI SQL standard requirement for the treatment of nulls in a multi-column FK. In any case Oracle specifically states this is the way FK work From the 10 Concepts manual, Ch 21 Data Integrity, topic Nulls and Foreign Keys:
    The relational model permits the value of foreign keys either to match the referenced primary or unique key value, or be null. If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key. <<HTH -- Mark D Powell --

  • ORA-02266: unique/primary keys in table referenced by enabled foreign keys

    Hi,
    I am trying to delete data from a table by dropping a partition. I have identified all the child tables by running the following command.
    select 'select count(*) from '||table_name||' where employee_id = 100;'
    from dba_constraints
    where constraint_type='R'
    and r_constraint_name in
    (select constraint_name from dba_constraints
    where constraint_type in ('P','U') and table_name='EMPLOYEE);
    'SELECTCOUNT(*)FROM'||TABLE_NAME||'WHEREEMPLOYEE_ID_ID=100;'
    select count(*) from PT_ORDERS where employee_id = 100;
    select count(*) from PT_DEP where employee_id = 100;
    select count(*) from PT_SKILLSET where employee_id = 100;
    I dropped the partition for employee_id 100 in all of the child tables. The select count(*) returns 0 rows for each of the above.
    When I try to run the below command on the EMPLOYEE table, I get 'ORA-02266: unique/primary keys in table referenced by enabled foreign keys'.
    alter table EMPLOYEE drop partition EMP_ID_100;
    I cant see why I am unable to drop this partition now as there is now child data in any of the referenced tables. Any suggestions or help on this would be greatly appreciated.
    Thanks.
    Rgs,
    Rob

    You should disable foreign key constraints first and drop partition. Deletion of rows or dropping partitions in childs don't work in this case
    as you have the global dependency:
    <PRE>
    SQL> create table scott.t (x int primary key, y int)
    2 partition by list (y) (
    3 partition p_1 values(1), partition p_2 values(2))
    4 /
    Table created.
    SQL> create table scott.t_c (x int references scott.t(x), y int)
    2 partition by list (y) (
    3 partition p_1 values(1), partition p_2 values(2))
    4 /
    Table created.
    SQL> insert into scott.t values(1,1)
    2 /
    1 row created.
    SQL> insert into scott.t values(2,2)
    2 /
    1 row created.
    SQL> insert into scott.t_c values(1,1)
    2 /
    1 row created.
    SQL> insert into scott.t_c values(2,2)
    2 /
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> alter table scott.t_c drop partition p_2;
    Table altered.
    SQL> alter table scott.t drop partition p_2;
    alter table scott.t drop partition p_2
    ERROR at line 1:
    ORA-02266: unique/primary keys in table referenced by enabled foreign keys
    SQL> select constraint_name from dba_constraints
    2 where owner = 'SCOTT' and constraint_type = 'P'
    3 and table_name = 'T';
    CONSTRAINT_NAME
    SYS_C0011058
    SQL> select constraint_name from dba_constraints
    2 where owner = 'SCOTT' and constraint_type = 'R'
    3 and r_constraint_name = 'SYS_C0011058';
    CONSTRAINT_NAME
    SYS_C0011059
    SQL> alter table scott.t_c disable constraint SYS_C0011059;
    Table altered.
    SQL> alter table scott.t drop partition p_2;
    Table altered.
    SQL> alter table scott.t_c enable novalidate constraint SYS_C0011059;
    Table altered.
    </PRE>
    I guess you should consider such option as Referencial partitioning (with some restrictions).
    Best wishes,
    Dmitry.

  • Does a foreign key have to be a primary key

    Hey all.I was checking on the database code written by sambapos.To my surprise, I found a foreign key that is not a primary key anywhere.
    Is that possible?
    If, so why?
    I am really astonished.

    Limitations and Restrictions
    A foreign key constraint does not have to be linked only to a primary key constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
    When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column; otherwise, a foreign key violation error message is returned. To make sure that all values of a composite foreign key constraint
    are verified, specify NOT NULL on all the participating columns.
    FOREIGN KEY constraints can reference only tables within the same database on the same server. Cross-database referential integrity must be implemented through triggers. For more information, see
    CREATE TRIGGER (Transact-SQL).
    FOREIGN KEY constraints can reference another column in the same table. This is referred to as a self-reference.
    A FOREIGN KEY constraint specified at the column level can list only one reference column. This column must have the same data type as the column on which the constraint is defined.
    A FOREIGN KEY constraint specified at the table level must have the same number of reference columns as the number of columns in the constraint column list. The data type of each reference column must also be the same as the corresponding column in the column
    list.
    The Database Engine does not have a predefined limit on either the number of FOREIGN KEY constraints a table can contain that reference other tables, or the number of FOREIGN KEY constraints that are owned by other tables that reference a specific table.
    Nevertheless, the actual number of FOREIGN KEY constraints that can be used is limited by the hardware configuration and by the design of the database and application. We recommend that a table contain no more than 253 FOREIGN KEY constraints, and that it
    be referenced by no more than 253 FOREIGN KEY constraints.
    FOREIGN KEY constraints are not enforced on temporary tables.
    If a foreign key is defined on a CLR user-defined type column, the implementation of the type must support binary ordering. For more information, see
    CLR User-Defined Types.
    A column of type varchar(max) can participate in a FOREIGN KEY constraint only if the primary key it references is also defined as type
    varchar(max).
    Read this article
    http://msdn.microsoft.com/en-us/library/ms189049.aspx
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • Primary key foreign key remove problem

    hi expretrs,
    I create 5 tables in ddic.
    1. zpr_cmp Company Master
    2. zpr_dpt Department Master
    3. zpr_dsg Designation Master
    4. zpr_emp Employee master.
    5. zpr_slm Salary Master.
    Foreign key reference in zpr_emp from table 1,2 and 3 created and
    table zpr_emp has
    cmpcd, Company Code
    empcd, Employee Code
    dptcd , Department Code
    dsgcd Designation Code
    as key fields.
    I have upload data and create module pool and reports.
    My problem that hr person say that we want to change deptcd/dsgcd of employee (zpr_emp) and
    dptcd and dsgcd is as key fields in zpr_emp when i change the table zpr_emp and remove
    two key fields dptcd/dsgcd and active error display.
    I also try with se14 (Activate and Adjust database) but error still.
    how can i remove key field from zpr_emp and active table without loss data and without any change of
    module pool/reports
    pl. help

    Diagnosis
    ZPR_EMP table is defined as a check table. For reasons of consistency, changes to the primary key of the table are not allowed.
    Procedure
    If it is essential that you change the primary key, you must delete the relevant foreign keys. Refer to the where-used list to find all tables containing a field that is checked against this table. Delete the foreign keys for these fields.
    If necessary, maintain the deleted foreign keys again.
    Value table - It's a field in a domain it helps in domain level data validation.
    Check table - unlike value table it helps in feild level data validation.
    The relational data model contains not only tables, but also relationships between tables. These relationships are defined in the ABAP/4 Dictionary by foreign keys. An important function of foreign keys is to support data integrity in the relational data model. Foreign key fields may assume only those values allowed by the check table, in other words, values occurring in the primary key of the check table.
    A foreign key provides a link between two tables, for eg.,T1 and T2 by including a reference in table T1 to the primary key of table T2. For this purpose, Foreign key fields assigned to the primary key fields of T2 are included in T1. Table T1, which is the one being checked, is called a foreign key table, and table T2 is called a check table. The terms dependent (foreign key) table and referenced (check) table are also used.
    VALUE TABLE:If the domain of the check field has a value table, this is proposed by the system as check table in the foreign field maintenance. The key fields of the value table are in this case assigned fields of the foreign key table with the same domain. These fields may assume only those values allowed by the value table.
    The value range of the domain can be defined by specifying value table.All table fields referring to this domain can then be checked against the corresponding field of this value table.In order the check can be executed, a foreign key must be defined for the value table.

Maybe you are looking for

  • PSE 6 - fixed the organiser to work with raw now editor won't load

    Could use some pointers - tech savvy but no expert :-) Couldn't get the organiser to work with CR2 files from the canon 50D. Download camera raw 5.4 plug-in. Deleted old version to remove the two entries in plug-in issue. Organiser seems to work as e

  • Appointment creation in Gantt chart using BAPI

    Hi The transaction /ITS/WAP2  - maintains the appointment for a shipment number in Gantt chart. We need to do the same using a BAPI or IDOC in ECC. Anybody knows any BAPI or Idoc to do this in the background ? Regards Anandan

  • Black update from Nokia (when will we get it?)

    Everyone else is getting the Black update for Lumia. When will verizon be giving us the black update?

  • How to avoid present 302 page

              Hi,           In my app, I use jsp with servlet, and the servlet acts as the "traffic cop",           that is, the users fill up the form in jsp pages, and the jsp pages are submitted           (post) to this servlet, this servlet do some w

  • XML schema changes

    Hi, Can someone tell me whats the best way to handle XML schema changes if there are already XMLType tables creates using the schema? I checked the Oracle XML DB developer's guide but didnt find any information on updating schema. Thanks, Hiren