Bug: no constraints/foreign keys when Scripter.Prefetch = true

Kind of bug report, using assemblies version v11.0.0.0 and ScriptingOptions.DriAll = true.
When you have tables with foreign keys or other constraints, these are not scripted when you pass urns of all tables to Scripter.Script which has Prefetch property set to true. I believe this is due to a bug in prefetching.
To workaround, set Scripter.Prefetch = false. Strange enough, passing urns of subset of the tables works as well (even excluding one table only), which results in the "constraints are returned when passing single urn only" reported behavior.

Hi, sure, sorry for late reply.
This is the DB create script:
DROP DATABASE [TestDB]
USE [master]
GO
CREATE DATABASE [TestDB] CONTAINMENT = NONE ON PRIMARY
( NAME = N'TestDB', FILENAME = N'C:\Windows\Temp\Test.mdf' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON
( NAME = N'TestLG', FILENAME = N'C:\Windows\Temp\Test.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [TestDB] SET COMPATIBILITY_LEVEL = 110
GO
ALTER DATABASE [TestDB] SET ANSI_NULL_DEFAULT OFF
ALTER DATABASE [TestDB] SET ANSI_NULLS OFF
ALTER DATABASE [TestDB] SET ANSI_PADDING OFF
ALTER DATABASE [TestDB] SET ANSI_WARNINGS OFF
ALTER DATABASE [TestDB] SET ARITHABORT OFF
ALTER DATABASE [TestDB] SET AUTO_CLOSE OFF
ALTER DATABASE [TestDB] SET AUTO_CREATE_STATISTICS ON
ALTER DATABASE [TestDB] SET AUTO_SHRINK OFF
ALTER DATABASE [TestDB] SET AUTO_UPDATE_STATISTICS ON
ALTER DATABASE [TestDB] SET CURSOR_CLOSE_ON_COMMIT OFF
ALTER DATABASE [TestDB] SET CURSOR_DEFAULT GLOBAL
ALTER DATABASE [TestDB] SET CONCAT_NULL_YIELDS_NULL OFF
ALTER DATABASE [TestDB] SET NUMERIC_ROUNDABORT OFF
ALTER DATABASE [TestDB] SET QUOTED_IDENTIFIER OFF
ALTER DATABASE [TestDB] SET RECURSIVE_TRIGGERS OFF
ALTER DATABASE [TestDB] SET DISABLE_BROKER
ALTER DATABASE [TestDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
ALTER DATABASE [TestDB] SET DATE_CORRELATION_OPTIMIZATION OFF
ALTER DATABASE [TestDB] SET TRUSTWORTHY OFF
ALTER DATABASE [TestDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
ALTER DATABASE [TestDB] SET PARAMETERIZATION SIMPLE
ALTER DATABASE [TestDB] SET READ_COMMITTED_SNAPSHOT OFF
ALTER DATABASE [TestDB] SET HONOR_BROKER_PRIORITY OFF
ALTER DATABASE [TestDB] SET RECOVERY SIMPLE
ALTER DATABASE [TestDB] SET MULTI_USER
ALTER DATABASE [TestDB] SET PAGE_VERIFY CHECKSUM
ALTER DATABASE [TestDB] SET DB_CHAINING OFF
ALTER DATABASE [TestDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
ALTER DATABASE [TestDB] SET TARGET_RECOVERY_TIME = 0 SECONDS
ALTER DATABASE [TestDB] SET READ_WRITE
GO
USE [TestDB]
GO
CREATE TABLE [dbo].[KeySource] (
[ID] [smallint] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_Reservation] PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[KeyUse] (
[UseID] [smallint] NOT NULL,
[Row] [tinyint] NOT NULL,
[Column] [tinyint] NOT NULL,
CONSTRAINT [PK_KeySource] PRIMARY KEY CLUSTERED ([UseID] ASC, [Row] ASC, [Column] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_ReservationSeats] UNIQUE NONCLUSTERED ([Row] ASC, [Column] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[KeyUse] WITH CHECK ADD CONSTRAINT [FK_Source_Use] FOREIGN KEY([UseID]) REFERENCES [dbo].[KeySource] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [dbo].[KeyUse] CHECK CONSTRAINT [FK_Source_Use]
ALTER TABLE [dbo].[KeyUse] WITH CHECK ADD CONSTRAINT [FK_Use_Use] FOREIGN KEY([UseID], [Row], [Column]) REFERENCES [dbo].[KeyUse] ([UseID], [Row], [Column])
ALTER TABLE [dbo].[KeyUse] CHECK CONSTRAINT [FK_Use_Use]
This is the code:
ServerConnection serverConnection = new ServerConnection("server", "user", "pwd");
Server server = new Server(serverConnection);
Database database = server.Databases["TestDB"];
Urn[] urns = database.EnumObjects(DatabaseObjectTypes.Table).Rows.OfType<DataRow>().Select(r => new Urn((string)r["Urn"])).Take(2).ToArray();
Scripter s = new Scripter(server);
s.Options.DriAll = true;
StringCollection result = s.Script(urns);
This is the result:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[KeySource](
[ID] [smallint] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[KeyUse](
[UseID] [smallint] NOT NULL,
[Row] [tinyint] NOT NULL,
[Column] [tinyint] NOT NULL
) ON [PRIMARY]
Note that the constraints are missing.
As already noted, adding s.PrefetchObjects = false; line fixes this.
But let's do the magic way - supplying less Urns than there actually is tables. To test this, add a dummy table to the DB:
USE [TestDB]
CREATE TABLE [dbo].[DummyTable]([Test] [nchar](10) NULL) ON [PRIMARY]
Run the code again. Note that the Take(2) method limits the Urns supplied to the Scripter to the same set as before.
However, the result is now:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[KeySource](
[ID] [smallint] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_Reservation] PRIMARY KEY CLUSTERED
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[KeyUse](
[UseID] [smallint] NOT NULL,
[Row] [tinyint] NOT NULL,
[Column] [tinyint] NOT NULL,
CONSTRAINT [PK_KeySource] PRIMARY KEY CLUSTERED
[UseID] ASC,
[Row] ASC,
[Column] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_ReservationSeats] UNIQUE NONCLUSTERED
[Row] ASC,
[Column] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[KeyUse] WITH CHECK ADD CONSTRAINT [FK_Source_Use] FOREIGN KEY([UseID])
REFERENCES [dbo].[KeySource] ([ID])
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE [dbo].[KeyUse] CHECK CONSTRAINT [FK_Source_Use]
ALTER TABLE [dbo].[KeyUse] WITH CHECK ADD CONSTRAINT [FK_Use_Use] FOREIGN KEY([UseID], [Row], [Column])
REFERENCES [dbo].[KeyUse] ([UseID], [Row], [Column])
ALTER TABLE [dbo].[KeyUse] CHECK CONSTRAINT [FK_Use_Use]
By testing on larger database I have noticed it does not really matter which table is excluded from the list.
Hope this helps,
Jan

Similar Messages

  • Unable to choose foreign key when creating reference partition

    Hello
    I have 2 foreign keys on a table. I am trying to choose the 2nd foreign key when creating a reference partition. I am unable to select the required foreign key.
    The model has Table A -> Table B -> Table C. Table A has a list partition. Table B is the child of Table A. I created a reference partition on Table B. Table C is child of Table B. There are 2 FKs on table C. I am unable to choose the required FK to create reference partition on table C.
    SQL Developer version - 3.0.0.665
    Any help would be appreciated.

    Hi,
    The FK that can be selected is normally the oldest FK that was created for the Table.
    So one option would be to delete and then recreate the FK that is selectable. This process may need to be repeated if there are several FKs that are "older" than the one you wish to use for Reference Partitioning.
    David

  • Can I create a foreign key when creating Business Components from Tables

    Hi,
    I would like to use ADF and JSF to create an application on our database. My problem is our database does not "conform". i.e. there are no foreign key constraints.
    When I create a "Business Component from Tables" view, can I put in my own joins between tables so enabling the use of the generated views?
    Jon L.

    View object instances show up in the data control palette once you've added them to your application module's data model.
    See these sections in the ADF Developer's Guide for more information:
    Section 2.6.3, "Using View Objects in the Application Module's Data Model" talks about using view object instance in the data model as part of the overview chapter.
    Section 4.5, "Understanding the Active Data Model" explains a little more about this
    Section 5.3, "Using a View Object in an Application Module's Data Model" shows how to do this.
    Chapter 10, "Overview of Application Module Data Binding" gives details on how the application and its view objects are exposed in the Data Control palette.
    You can find the guide on the ADF Learning Center on OTN.
    http://www.oracle.com/technology/products/adf/learnadf.html
    Look for the ADF Developer's Guide for Forms/4GL Developers.

  • Foreign Key Error script Generation

    here is
    CREATE table script
    create table employee_history
    (empl_id_hist number,
    empl_name varchar2(20)
    alter table employee_history
    add constraint emp_TO_empHIST foreign key (empl_id_hist)
    references employee (empl_id);
    Create table employee
    (empl_id number,
    ename varchar2(20));
    some empl_id_hist values not in Master table employee.
    now Foreign Key disabled.
    for checking not valid empl_id_hist ids
    I am trying to generate a script like this using Dynamic SQL.
    select unique empl_id_hist from employee_history
    where empl_id_hist not in (select empl_id from employee);
    but i am getting same Column empl_id_hist (instead of empl_id ) in Subquery too
    i.e
    select unique EMPL_ID_HIST from employee_history
    where EMPL_ID_HIST not in (select EMPL_ID_HIST from employee);
    DECLARE
    CNT NUMBER := 0;
    V_SQL_STR VARCHAR2(255);
    v_col_name VARCHAR2(255);
    v_ind CHAR(1);
    v_sql_where VARCHAR2(255);
    CURSOR C1 IS
    SELECT DECODE(c.position, 1, b.table_name, ' ') MASTER_TAB,
    DECODE(c.position, 1, a.table_name, ' ') CHILD_TAB,
    DECODE(c.position, 1, a.constraint_name, ' ') constraint_name,
    c.column_name colname
    from dba_constraints a,dba_constraints b, dba_cons_columns c
    where a.status = 'DISABLED'
    AND a.constraint_type = 'R'
    AND a.constraint_name = c.constraint_name
    and a.r_constraint_name = b.constraint_name (+)
    order by b.table_name, a.table_name, c.position;
    CURSOR c2(cons_name VARCHAR2) IS
    SELECT column_name FROM User_Cons_Columns
    WHERE constraint_name = cons_name
    ORDER BY column_name;
    BEGIN
    FOR R1 IN C1 LOOP
    v_col_name := '';
    BEGIN
    FOR r2 IN c2(r1.constraint_name) LOOP
    cnt := cnt + 1;
    IF cnt <= 1 THEN
    V_ind := 'y';
    V_SQL_sTR := 'SELECT UNIQUE A.'||R1.colname ||' FROM ' ||R1.CHILD_TAB ||' A' || chr(10);
    V_SQL_STR := V_SQL_STR ||'WHERE A.'||R1.colname ||' NOT IN ';
    V_SQL_STR := V_SQL_STR || '(SELECT B.'|| R1.colname ||' FROM ' || R1.MASTER_TAB ||' B);' ||chr(10);
    V_COL_NAME := V_COL_NAME || R2.COLUMN_NAME ||',';
    v_Sql_where := 'WHERE A.'||R2.COLUMN_NAME ||' = B.' || R2.COLUMN_NAME ||chr(10);
    ELSE
    v_ind := 'n';
    v_Sql_where := v_Sql_where || 'AND A.'||R2.COLUMN_NAME ||' = B.' || R2.COLUMN_NAME ||chr(10);
    V_COL_NAME := V_COL_NAME || R2.COLUMN_NAME ||',';
    END IF;
    END LOOP;
    v_sql_where := v_sql_where ||');';
    cnt := 0;
    END;
    IF v_ind = 'y' THEN
    DBMS_OUTPUT.PUT_LINE(V_SQL_sTR);
    ELSIF v_ind = 'n' THEN
    v_sql_str := '';
    v_col_name := SUBSTR(v_col_name,1,LENGTH(v_col_name) - 1) || '';
    V_SQL_STR := 'SELECT UNIQUE '|| V_COL_NAME ;
    V_SQL_STR := V_SQL_STR || ' FROM ' || R1.CHILD_TAB || ' A'|| CHR(10);
    V_SQL_STR := V_SQL_STR || 'WHERE NOT EXISTS ( '||CHR(10);
    V_SQL_STR := V_SQL_STR || 'SELECT 1 FROM ' ||R1.MASTER_TAB ||' B';
    DBMS_OUTPUT.PUT_LINE(V_SQL_STR);
    DBMS_OUTPUT.PUT_LINE(V_SQL_WHERE);
    DBMS_OUTPUT.PUT_LINE('');
    END IF;
    v_ind := '';
    END LOOP;
    END;
    thanks in advance

    That's because with this cursor
    CURSOR c2(cons_name VARCHAR2) IS
    SELECT column_name FROM User_Cons_Columns
    WHERE constraint_name = cons_name
    ORDER BY column_name;You assume that the column names are the same in both tables. You will need to read from user_cons_columns twice, once with the fk constraint name, once with the pk constraint name.
    SQL> create table parent (id number constraint parent_pk primary key) ;
    Table cr&eacute;&eacute;e.
    SQL> create table child (child_id number,
      2                      constraint child_fk1 foreign key (child_id)
      3                      references parent (id)
      4                     ) ;
    Table cr&eacute;&eacute;e.
    SQL> select
      2     a.column_name as parent_column_name,
      3     b.column_name as child_column_name
      4   from
      5     user_cons_columns a, user_cons_columns b
      6   where
      7     a.constraint_name = 'PARENT_PK'
      8     and b.constraint_name = 'CHILD_FK1'
      9     and a.position = b.position
    10   order by
    11     a.position ;
    PARENT_COLUMN_NAME             CHILD_COLUMN_NAME
    ID                             CHILD_ID

  • ORA-02292: integrity constraint - foreign key delete

    I am getting the above error message when attempting to delete an entry with a foreign key constraint. I have the standard delete button and the standard DML process for inset, update, delete, and a page validation conditioned on the delete button for EXISTS with the following code:
    select 1 from dual
    where (select count(*) from mdeccommitments
    where producer = :P25_COREID
    and receiver = :P25_COREID) = 0
    and (select count(*) from mdecbriefcal
    where primarytarget = :P25_COREID
    and primaryowner = :P25_COREID) = 0
    This code works in SQL directly. However, when I try to run this, I do not get the inline error associated with the validation routine, I just get the popup for the delete and then the very user-unfriendly Oracle error, almost as if the validation wasn't there. I tried removing the popup associated with the delete button, but it did not make a difference.
    I want to provide a friendly intercept and return. I do not want to cascade the delete. What am I missing here?
    Thanks.
    Gillian

    Thanks Varad, by running the debug, I realized I misinterpreted what the validation did - I had used EXISTS instead of NOT EXISTS. Making this change resulted in the correct processing. Being a newbie, I wasn't sufficiently familiar with the debug option to think about it.

  • Lost about 60-75% of my primary and foreign keys when Migrating from SQL Server 7

    Hi All,
    I did an almost successful migration between SQL Server 7.0 and Oracle9i.
    What happened:
    I seem to have lost my primary and foreign keys in the migration. The funny thing is when I viewed the constraints and indexes in Toad, they were there. However when I tried to enabled those constraints nothing happened.
    I really don't know how I can fixed this, but I don't understand why I didn't get a warning or an error message in the Migration Workbench (latest version).
    I did ignore the following errors, could that have anything to do with the keys being lost.
    Failed to create User:omwb_emulation; ORA-1920: user name "OMWB_EMULATION" conflicts with another user or role name
    Failed to create User:guest;ORA-01920: user name "GUEST" conflicts with another user or role name
    These users do not own any objects therefore I ignored them.
    Please advise
    Thanks

    Hi Joe,
    Not sure why you are able to see these objects and yet not able to enable them. Did you encounter any errors during the create Oracle Model phase?? Did you encounter any errors during the final Migrate phase?
    Also, it is really important to have a tablespace created before an attempt is made to create tables and indexes in the destination Oracle database.
    Regards
    John

  • Check constraint/foreign key combination

    I would like to add a constraint (check, FK, or otherwise) that forces a value to be either -1 OR be in a foreign table.  The statement below is invalid because you can't use subqueries, but I think it's clear what I'm trying to do.  Can anyone
    suggest a different approach?
    Thanks!
    ALTER TABLE cfg.ClientFieldThreshold ADD CONSTRAINT CK_cfg_ClientFieldThreshold_DBListID
    CHECK (DBListID = -1 OR DBListID IN (SELECT ID FROM dbo.vwClientDatabases)
    /* the subquery here isn't allowed */

    3 ways to do this. 
    1) use NULL instead of -1 as the value that does not have to be in the foreign table.  Then you just need a normal foreign key (because a foreign key column that contains NULL is not checked against the foreign table.  Sample code to do this
    Create Table FooParent(ParentID int primary key);
    Create Table FooChild(ChildId int primary key, ParentID int Null, Constraint FooChildFK Foreign Key(ParentID) References FooParent);
    go
    -- Can add row with NULL
    Insert FooChild(ChildId, ParentID) Values (1, Null);
    go
    -- But cannot add row with any other value that is not in FooParent
    Insert FooChild(ChildId, ParentID) Values (2, 25);
    go
    -- Check result
    Select * From FooChild;
    go
    Drop Table FooChild;
    go
    Drop Table FooParent;
    2) Add a dummy row to the parent table with a primary key of -1.  Then, of course, all you need is a foreign key constraint.
    3) Add a persisted computed column that is NULL whenever your column that you want to enforce the constraint against is equal to -1, otherwise just the value in that column.  Then create a foreign key on the computed column.  Sample code
    Create Table FooParent(ParentID int primary key);
    Create Table FooChild(ChildId int primary key, ParentID int Not Null, AlteredParentID As NULLIF(ParentID, -1) Persisted, Constraint FooChildFK Foreign Key(AlteredParentID) References FooParent);
    go
    -- Can add row with -1
    Insert FooChild(ChildId, ParentID) Values (1, -1);
    go
    -- But cannot add row with any other value that is not in FooParent
    Insert FooChild(ChildId, ParentID) Values (2, 25);
    go
    -- Check result
    Select * From FooChild;
    go
    Drop Table FooChild;
    go
    Drop Table FooParent;
    Tom

  • Accurate statistics on skewed foreign key when coming from parent

    Hi,
    I will be as short as possible:
    - we have two tables in a parent - child relationship. The foreign key is very skewed and we need to get child details coming from the parent
    - CBO is not considering the skeweness from histograms on foreign key column (I suppose it cannot as it is the example without going into tables) and it calculates the expected returning rows in the execution plan as no_rows / distinct_values => 10,000 / 3 = 3,333 rows for both execution plans, even if they returns effectively 1 row / 9,999 rows. In histograms exists this information but it cannot be extracted by CBO as it is.
    Any idea how to help CBO to choose separate execution plans for query 1 and query 2 excluding hints or query modifications?
    -- Oracle Database 10.2.0.3
    --DROP TABLE child;
    --DROP TABLE parent;
    CREATE TABLE parent AS SELECT LEVEL parent_num, 'parent_' || LEVEL parent_id FROM DUAL CONNECT BY LEVEL <= 10;
    ALTER TABLE parent ADD CONSTRAINT parent_pk PRIMARY KEY (parent_num);
    CREATE UNIQUE INDEX parent_id_ix ON PARENT (parent_id, parent_num);
    CREATE TABLE child AS SELECT DECODE (LEVEL, 1, 1, 10000, 10, 5) parent_num, 'child_' || LEVEL child_id FROM DUAL CONNECT BY LEVEL <= 10000;
    ALTER TABLE child ADD FOREIGN KEY (parent_num) REFERENCES parent (parent_num) ON DELETE CASCADE;
    CREATE INDEX child_parent_num_ix ON CHILD(parent_num);
    exec dbms_stats.gather_table_stats(ownname=>'***REPLACE WITH YOUR OWN USER***',tabname=>'PARENT',estimate_percent=>100,cascade=>TRUE,method_opt=>'FOR ALL COLUMNS SIZE 1');
    exec dbms_stats.gather_table_stats(ownname=>'***REPLACE WITH YOUR OWN USER***',tabname=>'CHILD',estimate_percent=>100,cascade=>TRUE,method_opt=>'FOR COLUMNS parent_num SIZE 3, child_id SIZE 1');
    -- QUERY 1: this query should be very selective (1 row), using index
    SELECT c.child_id FROM child c, parent p WHERE c.parent_num = p.parent_num AND p.parent_id = 'parent_1';
    -- QUERY 2: it should return 99.9999% of the rows (9,999 rows), so it should use full table scan
    SELECT c.child_id FROM child c, parent p WHERE c.parent_num = p.parent_num AND p.parent_id = 'parent_5';
    In reality both queries have the same execution plan as below:
    Execution Plan
    Plan hash value: 4033709836
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 3333 | 83325 | 6 (0)| 00:00:01 |
    | 1 | NESTED LOOPS | | 3333 | 83325 | 6 (0)| 00:00:01 |
    | 2 | TABLE ACCESS BY INDEX ROWID| PARENT | 1 | 12 | 1 (0)| 00:00:01 |
    |* 3 | INDEX UNIQUE SCAN | PARENT_ID_IX | 1 | | 0 (0)| 00:00:01 |
    |* 4 | TABLE ACCESS FULL | CHILD | 3333 | 43329 | 5 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    3 - access("P"."PARENT_ID"='parent_1')
    4 - filter("C"."PARENT_NUM"="P"."PARENT_NUM")
    Execution Plan
    Plan hash value: 4033709836
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    | 0 | SELECT STATEMENT | | 3333 | 83325 | 6 (0)| 00:00:01 |
    | 1 | NESTED LOOPS | | 3333 | 83325 | 6 (0)| 00:00:01 |
    | 2 | TABLE ACCESS BY INDEX ROWID| PARENT | 1 | 12 | 1 (0)| 00:00:01 |
    |* 3 | INDEX UNIQUE SCAN | PARENT_ID_IX | 1 | | 0 (0)| 00:00:01 |
    |* 4 | TABLE ACCESS FULL | CHILD | 3333 | 43329 | 5 (0)| 00:00:01 |
    Predicate Information (identified by operation id):
    3 - access("P"."PARENT_ID"='parent_5')
    4 - filter("C"."PARENT_NUM"="P"."PARENT_NUM")
    column table_name format A10
    column column_name format A11
    column endpoint_actual_value format A21
    select * from user_tab_histograms where table_name='CHILD' and column_name='PARENT_NUM';
    TABLE_NAME COLUMN_NAME ENDPOINT_NUMBER ENDPOINT_VALUE ENDPOINT_ACTUAL_VALUE
    CHILD PARENT_NUM 1 1
    CHILD PARENT_NUM 9999 5
    CHILD PARENT_NUM 10000 10
    3 rows selected.
    I am sorry about the formatting but this is the best I could following plain text help.
    Thank you,
    Eugen
    Edited by: Eugen Iacob on Dec 13, 2011 3:21 AM
    Edited by: Eugen Iacob on Dec 13, 2011 12:36 PM
    Edited by: Eugen Iacob on Dec 13, 2011 12:37 PM
    Edited by: Eugen Iacob on Dec 14, 2011 2:13 AM

    Hi,
    you can create a function based index on child table, and query that value instead of parent_id from parent table.
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE     10.2.0.1.0     Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    CREATE TABLE parent AS SELECT LEVEL parent_num, 'parent_' || LEVEL parent_id, 'some text ' || level parent_name
    FROM DUAL CONNECT BY LEVEL <= 10;
    ALTER TABLE parent ADD CONSTRAINT parent_pk PRIMARY KEY (parent_num);
    CREATE UNIQUE INDEX parent_id_ix ON PARENT (parent_id, parent_num);
    CREATE TABLE child AS SELECT DECODE (LEVEL, 1, 1, 10000, 10, 5) parent_num, 'child_' || LEVEL child_id,
    'some text ' || level child_name
    FROM DUAL CONNECT BY LEVEL <= 10000;
    ALTER TABLE child ADD FOREIGN KEY (parent_num) REFERENCES parent (parent_num) ON DELETE CASCADE;
    CREATE INDEX child_parent_num_ix ON CHILD(parent_num);
    CREATE OR REPLACE function get_parent_id( in_parent_num in number )
    RETURN parent.parent_id%TYPE
    DETERMINISTIC
    IS
      ret parent.parent_id%TYPE;
    BEGIN
      SELECT parent_id INTO ret
      FROM parent
      WHERE parent_num = in_parent_num;
      RETURN ret;
    END;
    CREATE INDEX child_parent_id_idx ON child( get_parent_id( parent_num ) );
    exec dbms_stats.gather_table_stats(ownname=>user,tabname=>'CHILD',estimate_percent=>100,cascade=>TRUE,method_opt=>'FOR ALL HIDDEN COLUMNS');
    explain plan for
    SELECT p.parent_name, c.child_name
    FROM child c, parent p
    WHERE c.parent_num = p.parent_num AND get_parent_id(c.parent_num ) = 'parent_1';
    select * from table( dbms_xplan.display );
    plan FOR succeeded.
    PLAN_TABLE_OUTPUT                                                                                                                                                                                                                                                                                           
    Plan hash value: 3790918082                                                                                                                                                                                                                                                                                 
    | Id  | Operation                    | Name                | Rows  | Bytes | Cost (%CPU)| Time     |                                                                                                                                                                                                        
    |   0 | SELECT STATEMENT             |                     |     1 |    77 |     3   (0)| 00:00:01 |                                                                                                                                                                                                        
    |   1 |  NESTED LOOPS                |                     |     1 |    77 |     3   (0)| 00:00:01 |                                                                                                                                                                                                        
    |   2 |   TABLE ACCESS BY INDEX ROWID| CHILD               |     1 |    37 |     2   (0)| 00:00:01 |                                                                                                                                                                                                        
    |*  3 |    INDEX RANGE SCAN          | CHILD_PARENT_ID_IDX |     1 |       |     1   (0)| 00:00:01 |                                                                                                                                                                                                        
    |   4 |   TABLE ACCESS BY INDEX ROWID| PARENT              |     1 |    40 |     1   (0)| 00:00:01 |                                                                                                                                                                                                        
    |*  5 |    INDEX UNIQUE SCAN         | PARENT_PK           |     1 |       |     0   (0)| 00:00:01 |                                                                                                                                                                                                        
    Predicate Information (identified by operation id):                                                                                                                                                                                                                                                         
       3 - access("TEST"."GET_PARENT_ID"("PARENT_NUM")='parent_1')                                                                                                                                                                                                                                              
       5 - access("C"."PARENT_NUM"="P"."PARENT_NUM")                                                                                                                                                                                                                                                            
    Note                                                                                                                                                                                                                                                                                                        
       - dynamic sampling used for this statement                                                                                                                                                                                                                                                               
    22 rows selected
    explain plan for
    SELECT  p.parent_id, c.child_id
    FROM child c, parent p
    WHERE c.parent_num = p.parent_num AND get_parent_id(c.parent_num ) = 'parent_5';
    select * from table( dbms_xplan.display );
    plan FOR succeeded.
    PLAN_TABLE_OUTPUT                                                                                                                                                                                                                                                                                           
    Plan hash value: 2656363181                                                                                                                                                                                                                                                                                 
    | Id  | Operation          | Name         | Rows  | Bytes | Cost (%CPU)| Time     |                                                                                                                                                                                                                         
    |   0 | SELECT STATEMENT   |              |  9998 |   732K|    23  (27)| 00:00:01 |                                                                                                                                                                                                                         
    |*  1 |  HASH JOIN         |              |  9998 |   732K|    23  (27)| 00:00:01 |                                                                                                                                                                                                                         
    |   2 |   INDEX FULL SCAN  | PARENT_ID_IX |    10 |   380 |     1   (0)| 00:00:01 |                                                                                                                                                                                                                         
    |*  3 |   TABLE ACCESS FULL| CHILD        |  9998 |   361K|    21  (24)| 00:00:01 |                                                                                                                                                                                                                         
    Predicate Information (identified by operation id):                                                                                                                                                                                                                                                         
       1 - access("C"."PARENT_NUM"="P"."PARENT_NUM")                                                                                                                                                                                                                                                            
       3 - filter("GET_PARENT_ID"("C"."PARENT_NUM")='parent_5')                                                                                                                                                                                                                                                 
    Note                                                                                                                                                                                                                                                                                                        
       - dynamic sampling used for this statement                                                                                                                                                                                                                                                               
    20 rows selected

  • FOREIGN KEY CONSTRAINT

    HI GUYS
    I DID THE FOLL
    CREATE TABLE MASTER(EMPNO NUMBER PRIMARY KEY,
    ENAME VARCHAR2(12));
    CREATE TABLE CHILD(EMPNO NUMBER);
    ALTER TABLE CHILD ADD CONSTRAINT FOREIGN KEY REFERNCES MASTER(EMPNO)
    NOW WHEN I DOTHE ABOVE AND THE DO DESC CHILD
    I GET THE FOLL
    EMPNO NUMBER
    ENAME VARCHAR2(12)
    KEY NUMBER
    WHAT IS THIS KEY COLUMN ? WHY IS IT COMING
    KINDLY CLARIFY

    Interesting.
    The correct syntax to add a FK constraint is:
    ALTER TABLE child ADD CONSTRAINT
       FOREIGN KEY (empno) REFERENCES master (empno);I can replicate your behaviour in 9.2.0.6, and in 8.1.7.4. It appears that in the absence of a column list in parens, Oracle takes the word after FOREIGN and adds a column with that name and the appropriate data type to the table and uses that in the FK.
    SQL> CREATE TABLE master (empno NUMBER PRIMARY KEY,
      2                       ename VARCHAR2(12));
    Table created.
    SQL> CREATE TABLE child (empno NUMBER);
    Table created.
    SQL> ALTER TABLE child ADD CONSTRAINT
      2     FOREIGN new_col REFERENCES master (empno);
    Table altered.
    SQL> desc child
    Name                                      Null?    Type
    EMPNO                                              NUMBER
    NEW_COL                                            NUMBERJust to show that the constraint is enforced:
    SQL> INSERT INTO child VALUES(1,1);
    INSERT INTO child VALUES(1,1)
    ERROR at line 1:
    ORA-02291: integrity constraint (OPS$ORACLE.SYS_C0070911) violated -
    parent key not foundBut, this only works when there is no KEY keyword:
    SQL> DROP TABLE child;
    Table dropped.
    SQL> CREATE TABLE child (empno NUMBER);
    Table created.
    SQL> ALTER TABLE child ADD CONSTRAINT
      2     FOREIGN KEY new_col REFERENCES master (empno);
       FOREIGN KEY new_col REFERENCES master (empno)
    ERROR at line 2:
    ORA-00902: invalid datatypeOn a fast scan of the documentation I don't see where this behaviour is documented, and I have certainly never seen this before. Anyone out there have any thoughts?
    John

  • Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

    I am trying to introduce a constraint on the sales_details table
    ALTER TABLE [dbo].[SALES_DETAILS] WITH CHECK ADD constraint fk_sd_vat FOREIGN KEY([VAT])
    REFERENCES [dbo].[VAT Rate] ([VAT]) on update cascade on delete cascade
    GO
    I am getting the error saying
    Msg 1785, Level 16, State 0, Line 1
    Introducing FOREIGN KEY constraint 'fk_sd_vat' on table 'SALES_DETAILS' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
    Msg 1750, Level 16, State 0, Line 1
    Could not create constraint. See previous errors.
    What could be the reason,Please suggest me the solution for  this,
    Thanks,

    Hi Erland,
    This is my DDl
    CREATE TABLE [dbo].sales_details(
    [BNUM] [varchar](20) NOT NULL,
    [CNAME] [varchar](30) NOT NULL,
    [CNUM] [int] NOT NULL FOREIGN KEY([CNUM])REFERENCES [dbo].[Customer] ([CNum]),
    [ITNAME] [varchar](100) NOT NULL,
    [ITEM#] [int] NOT NULL ,
    [QTY] [int] NOT NULL,
    [UNIT] [varchar](5) NOT NULL,
    [PRICE] [float] NOT NULL,
    [BASIC] [float] NOT NULL,
    [DISCOUNT] [float] NOT NULL,
    [FRQTY] [int] NOT NULL,
    [BADDR] [varchar](300) NULL,
    [CADDR] [varchar](300) NOT NULL,
    [BDATE] [datetime] NOT NULL,
    [VAT] [float] NOT NULL
    ALTER TABLE [dbo].[SALES_DETAILS] WITH CHECK ADD constraint cons1 FOREIGN KEY([ITNAME])
    REFERENCES [dbo].[New Item] ([Item Description]) on cascade update
    GO
    ALTER TABLE [dbo].[SALES_DETAILS] WITH CHECK ADD constraint FOREIGN KEY([VAT])
    REFERENCES [dbo].[VAT Rate] ([VAT]) on cascade update
    GO
    I am getting the error when i execute second Alter statement.
    Thanks,
    Check if VAT Rate table has any FK with cascaded options?
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • SQL Developer Data Modeler - Relation to Foreign Key Generation

    SQL Developer Data Modeler 2.0.0 Build 584.
    I am having trouble with Relations to Foreign Keys when Forward Engineering a Relational Model from a Logical Model.
    First of all, the Naming Standard is not applied to the Foreign Keys when I perform the Engineer to Relational Model.
    So I right click on the Relational Model from the Browser and Apply Naming Standards to Keys and Constraints.
    I uncheck everything but Foreign Keys.
    Now, Foreign Keys are named according to my Naming Standards.
    However, this process also performs renames on the Column Foreign Keys even though I specifically unchecked that option.
    This appears to be a BUG in the software and I haven't found a way around it.
    I tried using {column} instead of {ref column} in the Naming Standard Template for Column Foreign Key, but that simply resulted in renaming my columns to "{column}".
    Please confirm and/or let me know of any work-around for this.
    Thanks,
    Dan

    Hi Philip,
    Thanks for the reply.
    Is this recorded as a bug to be addressed in the future?
    Should I submit this problem via Oracle Support?
    The other work-around I came up with is to override every Relation name in the Logical Model with the name I want to use in the Relational Model.
    When the Relational Model is Engineered, this becomes my Foreign Key name.
    Of course, this is not how I want to do things, so I am hoping for a bug fix someday.
    Regards,
    Dan

  • Disabling Foreign keys before Insert

    DB version:10gR2
    Is it a standard practice to disable Foreign keys when you have Huge INSERTs . Is there performance enhancement by deferring the Foreign key Check during Huge INSERTs?
    Our client want to disable the FKs before a huge INSERT. They say they can manually rectify all issues related to Foreign key violation resulting from Disabling the FK.
    What do you guys reckon?

    It should hapen an enhancement performance by deferring the Foreign key Check during Huge INSERTs.
    The same thing with triggers.
    If you are sure that data that you want to insert is not inconsistent with the data on the DB, or that you manually rectify inconsistencies after the insert, then there is no problem by disabling Foreign key constraints/triggers.
    Also there are gains of performance if you drop of the indices (if there's any) and recreate after the Huge INSERT.
    Regards.

  • Create a foreign key from a field that is part of a mulitple primary key

    Hi,
    i had a table named T_A, with a double primary key : (A,B)
    Then i created a table named T_B with a field : C.
    I want this field T_B.C to take only values that already exist in field T_A.A.
    So i tried to create a foreign key on my field T_B.C, pointing on the field T_A.A : an error message appeared "not possible to create a foreign key on a field that is not a primary key".
    How can i solve this....? If U have any idea, please mail me !!
    THANX very much.

    Add column A as foreign key into the table T_BHow?
    (was the question from the original poster. Adding a column to table T_B that happen to have same name as the corresponding column in table T_A would not allow you to add the foreign key).
    SQL> create table t_a (a number, b number, primary key(a, b)) ;
    Table created.
    SQL> create table t_b(a number, c number, constraint foreign key references t_a(a)) ;
    create table t_b(a number, c number, constraint foreign key references t_a(a))
    ERROR at line 1:
    ORA-02270: no matching unique or primary key for this column-list
    SQL>

  • Generated Script fails when attempting to drop Foreign Key Constraint

    I made some changes to my database.  I used the generate script process to generate a drop and create script to these tables.  The generated script first ran Alter Table Drop Constraints to drop the Foreign Key constraints and then did Drop tables
    and then did create table to construct the script with the proper changes.
    However, when we attempted to run the script, all of the Drop constraint statements failed reporting that there was no such constraint.  Then the drop table scripts failed because of the existence of the very foreign key constraints  that SQL Server
    had just stated did not exist.
    BOL states that the statement "DROP { [ CONSTRAINT ] constraint_name | COLUMN column_name } " is  "Used in a CHECK, FOREIGN KEY, UNIQUE, or PRIMARY KEY constraint."  So why couldn't I drop those specified Foreign
    Key constraints in a script generated by SQL Server itself.
    Edward R. Joell MCSD MCDBA

    Are you sure there are no Constraints on other tables which are causing your issue?
    If a foreign key from table abc refences table def it will cause the drop to fail.
    If your script is already attempting to drop such constraints, have you checked that they are dropping from the correct table (and not the table that would be the target of the drop)?
    I discovered two things yesterday and one thing today about generated scripts.
    When you generated a script to drop and create a set of tables and you mark it to include foreign keys, the generated script will first create a set a scripts to drop the foreign keys , then will create a set of statements for each table that will,
    first, again drop the same foreign keys that it did earlier, then drop the table.  If there is no "if exists" statement for each statement, the drop constraint will fail.
    The script generated by the generate scripts wizard, even when you set the Drop and Create option in the advanced tab, unlike the scripts generated when you right click a table and select Drop and Create from the context menu, does not by default create
    an "If Exists" statement before the attempt to drop anything.
    You can make the generate Scripts wizard generate an "if exists" statement by changing the "Include if NOT EXISTS" option on the advanced tab to true. However, while the script generator will find all of the foreign keys that show that
    table as the parent_id, it will not show the FK constraints on tables which are not being dropped and created.  Nor can you find them by querying the sys.foreign_keys view using the standard type of Foreign Key "If Exists" statement because
    it would do a query like
    SELECT *
    FROM sys.foreign_keys
    WHERE object_id = OBJECT_ID(N'[dbo].[FK_prc_ContractSubLines_prc_PRSubLines]')
    AND parent_object_id = OBJECT_ID(N'[dbo].[prc_ContractSubLines]')
    And the script generator does not care even if you show an option like "Generate Scripts For Dependent Objects", it will not generate a drop script for the foreign constraints on other tables that reference your table.  I have not even found
    a way to get back the results of a query on the sys.foreign_keys view that will show those keys that reference your table. The only thing I been able to do is to open the table in design and check out the list of relationships in your table and see open each
    relationship and see which table is the "foreign key table" rather than the primary key table. This will make writing drop and create scripts very very long and tedious. As you would have to  create addional Alter tables scripts to do a drop
    and create foreign keys on each table referencing yours and manually place them into your scripts at correct locations. This is almost as bad as the Oracle SQL Developer's generate script results which (at least in 2010) so screws up the order of the generated
    script that it is trying to create foreign keys on tables it has not created yet.
    So Patrick I see that you thought about the foreign keys on other tables.  I wish I had read your post before spending the morning troubleshooting this issue based on this morning's script that ran and crashed embarrassingly. 
    I would like to know if someone has a query to reveal all of the foreign keys that reference your table from another table using the sys views.  As it is I have to open each table in design to get a list of FKs that reference it.
    Edward R. Joell MCSD MCDBA

  • Publish: dropping index when it is used for foreign key constraint enforcement

    Hi,
    I'm trying to update a target schema from a reference database via Publish. Among the changes to apply, there's an index that needs to be dropped. Since it's linked to a foreign key constraint, it cannot be deleted unless the foreign key is temporarily dropped
    (I saw somewhere that disabling the foreign key should be enough but it doesn't seem to work either).
    Since there are other changes to be made on the same table, this foreign key also has to be dropped before the script can delete the table and re-create it. This part of the script is correctly generated. The problem is that this part appears after the 'DROP
    INDEX' instruction.
    So when generating the update script, SSDT tries to drop the index BEFORE dropping the foreign key. And I can't drop the foreign key in my custom pre-deployment script, otherwise the update script would fail when trying to delete it again.
    Shouldn't SSDT be smart enough to drop the constraint before the index? Is it a bug or did I forget to set an option? If it's not a bug, what can I do apart from doing it manually?
    Thank you for your help

    Hi Elsa,
    That sounds like a bug. Could you please file a Connect issue for this at
    https://connect.microsoft.com/SQLServer/feedback/CreateFeedback.aspx using the category "Developer Tools (SSDT, BIDS, etc.)"? We're trying to track all bugs through
    Connect so that you can tell when we have fixed the issue and we can request more information.
    A workaround for this issue might be to write a pre-deployment script for your project to drop the foreign key prior to deployment. A pre-deployment script can be added to your project by right-clicking on the
    project in solution explorer and then clicking on Add > Script... and selecting Pre-Deployment Script from the list.
    Thanks!

Maybe you are looking for

  • Can I show a spinner when the images are loading

    I am now using flash builder 4.5.1 to create a mobile application. there will be multiple images in the view. I want to use  a spinner to indicate the image is loading, and once the image loaded,  the content of each image be replaced by the original

  • Should I use one apple id with multiple devices?

    I have 2 iPods an iPad and a new iPhone. Should I use the same Apple ID on all decvices?  The iPods are for the kids to use. Also, will be adding apple tv soon...

  • Help with Frameset and Browser differences

    I hope someone can help me with my Frameset. It works great in Safari but Firefox doesn't recognize the frames. I'm using Dreamweaver CS5.5, Mac OS10.8. Here's the link: http://tonyhertz.com/2012/Frameset_black_white_landscape_photo.html Thank you.

  • Concatenating to a variable more than once?

    Is it possible to concat to the same variable more than once? For some reason I am thinking not. I have the following: declare v_sql VARCHAR2(2000); v_sql := 'Select blah balh Where myfield in ('; if v_show1 = 1 then v_sql := v_sql || '1,' end if; if

  • No record found in the table while using condition for the new added field

    Hi, I have added a new field in Z table. There is lots of record in the table. The field which I added have null records. When I am checking the record using the condition new field equal(EQ) to space or blank. This shows no record in the table, but