To to see Foreign keys of a constraint

Hi
I have a table suppose Emp
which have primary key empno.
Now i want to see in how many tables empno use as foreign key.
Regards
Danish Hayder

select a.owner, ac.table_name, a.constraint_name,
ac.COLUMN_NAME, ac.POSITION,
A.R_OWNER, acr.table_name r_table_name, acr.CONSTRAINT_NAME r_constraint_name,
acr.COLUMN_NAME r_column_name , acr.position r_position
from all_constraints a, all_cons_columns ac
,all_constraints ar, all_cons_columns acr
where a.R_CONSTRAINT_NAME = ar.CONSTRAINT_NAME and a.R_OWNER = ar.OWNER and
a.constraint_type ='R' and ar.CONSTRAINT_type = 'P'
and a.CONSTRAINT_NAME = ac.CONSTRAINT_NAME and a.table_name= ac.table_name and a.OWNER = ac.OWNER
and ar.CONSTRAINT_NAME = acr.CONSTRAINT_NAME and ar.table_name= acr.table_name and ar.owner = acr.owner and
ac.position = acr.position and
ac.owner='HR'
order by table_name, constraint_name, position
I got this query from some where in this forum, may also be helpful to you in this regard. In the last ac.owner='HR' means name of schema.
Regards
Girish

Similar Messages

  • 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.

  • 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

  • Foreign keys without ON DELETE CASCADE; Database Design question

    This is the 3rd company i am working, where i see Foreign Keys created without
    ON DELETE CASCADEclause.
    My colleague says that it is created without ON DELETE CASCADE clause in order to make deletion of data (child records) difficult. So, for Purge/Archive codes, before we delete from Parent table we have to delete from the Child table first.
    Occasinaly , something goes wrong and we'll end up disabling all FKs and then do Purging, Archiving, etc..
    So, isn't it better to create Foreign keys with ON DELETE CASCADE clause rather than having all these hassles?
    From you experience, what do you guys think?

    ON DELETE CASCADE is usually not a good idea - something 'magical' happens in the background and rows go away. Instead, consider making the FK DEFERRABLE INITIALLY DEFERRED. That way you can delete the parent and child rows in any sequence and the constraint will not be checked until commit time. You want to use an API (stored procedure/package) to make sure DML is executed in the proper sequence and in the proper way for your business rules.

  • Questions about creating a foreign key on a large table

    Hello @ll,
    during a database update I lost a foreign key between two tables. The tables are called werteart and werteartarchiv_pt. Because of its size, werteartarchiv_pt is a partitioned table. The missing foreign key was a constraint on table werteartarchiv_pt referencing werteart.
    Some statistics about the sizes of the mentioned tables:
    werteart 22 MB
    werteartarchiv_pt 223 GB
    werteartarchiv_pt (Index) 243 GB
    I tried to create the foreign key again, but it failed with the following error (Excuses for the german error message):
    sqlplus ORA-00604: Fehler auf rekursiver SQL-Ebene 1
    sqlplus ORA-01652: Temp-Segment kann nicht um 128 in Tablespace TEMPS00 erweitert
    The statement I used:
    alter table werteartarchiv_pt
    add constraint werteartarchiv_pt_fk1
    foreign key (schiene, werteartadresse, merkmale)
    references werteart (schiene, werteartadresse, merkmale)
    on delete cascade
    initially deferred deferrable;
    So the problem seems to be, that Oracle needs a lot of temporary tablespace to generate the foreign key and I do not know how much and why.
    My questions now are, and hopefully someone is here, who can answer all or a part of it:
    1) Why does Oracle need temporary tablespace to create the foreign key? The foreign key uses the same columns like the primary key.
    2a) Is it possible to tweak the statement without using the temporary tablespace?
    2b) If it is not possible to avoid the usage of the temporary tablespace, is there a formula how to calculate the needed temporary tablespace?
    3) Is it possible to modify data in the tables while the foreign key is created or is the whole table locked during the process?
    Any help or hint is appreciated.
    Regards,
    Bjoern

    RollinHand wrote:
    My questions now are, and hopefully someone is here, who can answer all or a part of it:
    1) Why does Oracle need temporary tablespace to create the foreign key? The foreign key uses the same columns like the primary key.Because it's validating the data to ensure the foreign key won't be violated. If you had specified ENABLE NOVALIDATE when creating it then the existing data in the table wouldn't need to be checked and the statement should complete instantly (future data added would be checked by the constraint).
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/general005.htm
    Search for "Enable Novalidate Constraint State"

  • Is this a BUG???  Database Export not including Foreign Key Constraints

    I'm using SQL Developer 1.5.4 with both the 59.47 and 59.59 patches installed. I want to do a database export from a 10g XE schema, and include all objects in the resulting DDL. So, I select ALL the checkboxes in the export wizard and when I get to Step 3 to specify objects, I don't see any of my constraints in the listbox... no foreign key constraints, no primary key constraints, no check constraints, nothing. Is this a bug, or is there a workaround, or what could I possibly be doing wrong? We want to be able to use the database export feature to easily transport and track modifications to our entire schema using source control compare.
    Any help or alternate suggestions would be apprieciated.
    Thanks,
    Matt

    Thanks skutz, we just figured that out this morning. Also, it should be noted that you need to be logged in as the owner of the schema otherwise selecting nothing in the filter will give you nothing, but selecting items in the filter will give you those items even if you're not connected as the schema owner. I wonder if that is the detail of the Bug 8679318.
    Edited by: mattsnyder on Jul 14, 2009 9:24 AM

  • Query the name of the parent table in a foreign key constraint

    Hello,
    Does anyone know how to query for the parent table name in a foreign key constraint? I don't see that relationship in ALL_CONS_COLUMNS or ALL_CONSTRAINTS.
    Thanks in advance,
    Michael

    or try this...
    SELECT rc.TABLE_NAME "PK_Table_Name",cc.TABLE_NAME "FK_Table_Name",
           case when cc.column_name = rc.column_name
                then c.TABLE_NAME || '(' || cc.COLUMN_NAME || ')'
                else r.TABLE_NAME || '(' || rc.COLUMN_NAME || ') = ' ||c.TABLE_NAME || '(' || cc.COLUMN_NAME || ')' end as "TABLE_NAME(COLUMN_NAME)"
    from all_constraints c,
         all_constraints r,
         all_cons_columns cc,
         all_cons_columns rc
    WHERE
         r.table_name = upper('emp')
    and      c.CONSTRAINT_TYPE = 'R'
    and     c.R_OWNER = r.OWNER
    and     c.R_CONSTRAINT_NAME = r.CONSTRAINT_NAME
    and     c.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
    and     c.OWNER = cc.OWNER
    and     r.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
    and     r.OWNER = rc.OWNER
    and     cc.POSITION = rc.POSITION
    ORDER BY r.TABLE_NAME;

  • Foreign key mapped to a unique constraint

    ok here is the issue
    create table parent(col1 char, col2 char);
    alter table parent add constraint pk_parent primary key(col1);
    alter table parent add constraint uk_parent unique(col1,col2);
    insert into parent values('A','7');
    *1 row created.*
    create table child(col1 char, col2 char);
    alter table child add constraint fk_child_parent foreign key(col1,col2) references parent(col1,col2);
    insert into child values('B','4');
    insert into child values('B','4')
    ERROR at line 1:
    ORA-02291: integrity constraint (WILDGOD.FK_CHILD_PARENT) violated - parent key
    not found
    thats what i expect....but
    insert into child values('B',NULL);
    *1 row created.*
    why does it let me do this, i realize its because col2 is NULL but shouldnt it still check for col1 to be in the parent?
    Please clarify, thanks in advance.

    I see the same & am not sure why either.
    SQL> @a
    SQL> create table parent(col1 char, col2 char);
    Table created.
    SQL> alter table parent add constraint pk_parent primary key(col1);
    Table altered.
    SQL> alter table parent add constraint uk_parent unique(col1,col2);
    Table altered.
    SQL>
    SQL> insert into parent values('A','7');
    1 row created.
    SQL> create table child(col1 char, col2 char);
    Table created.
    SQL> alter table child add constraint fk_child_parent foreign key(col1,col2) references parent(col1,col2);
    Table altered.
    SQL>
    SQL> insert into child values('B','4');
    insert into child values('B','4')
    ERROR at line 1:
    ORA-02291: integrity constraint (DBADMIN.FK_CHILD_PARENT) violated - parent key not found
    SQL>
    SQL> insert into child values('B',NULL);
    1 row created.
    SQL>
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE     11.2.0.1.0     Production
    TNS for Linux: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production

  • 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 --

  • Primary Key and Foreign Key Constraints

    Hi All,
    I would like to know PRIMARY KEY and FOREIGN KEY constraints on existing oracle tables. Could any one suggest me how to find out.
    Thanks,
    RED

    You can query DBA_CONSTRAINTS to get a list of all the constraints on table A and/or table B. The documentation I linked to gives a full list of the data you can see in DBA_CONSTRAINTS, but it includes things like the referenced table name and referenced constraint name for a foreign key constraint. If A is a parent of B or B is a parent of A, you could match up the parent's primary key constraint to the child's foreign key constraint.
    More generally, though, if you don't know that one of the tables is a parent of the other, figuring out how to join the two tables is probably not something that can be done using just the Oracle data dictionary. You would probably need an understanding of the data model being used to figure out what intermediate table(s) needed to be joined in order to relate rows in A to rows in B.
    Justin

  • Foreign Key Constraint Failure on Self-Referencing Table

    In a recent data deletion project, I ran into a problem where Oracle allowed for a record (the parent) to be deleted when there still existed a child record in the same table which referred to the parent.
    An abbreviated version of the table is as follows:
    create table test (
    template_id number not null,
    customer_id number null,
    parent_id number null,
    constraint pk_test primary key (template_id),
    constraint r_parent foreign key (parent_id) references test (template_id));
    The parent and child records are as follows:
    Parent: template_id = 100, customer_id = 200, parent_id = null
    Child: template_id = 101, customer_id = null, parent_id = 100
    Records were deleted from this table using:
    DELETE FROM test WHERE customer_id = 200;
    When this statement is executed, is it being executed as part of 155 delete statements using PL/SQL, and tens of thousands of records from 155 tables are being deleted. These delete statements have been ordered taking into account foreign key constraints. All 155 statements are being deleted in a single transaction. The delete statement above was the 23rd statement of the set to be executed. I would have expected when this delete statement was executed, an error would have been thrown. However, all 155 delete statements successfully complete, and after committing the results, the child record above still exists in the DB as an orphan. I also tried executing the first 23 statements manually in SQL*Plus (still one transaction), and the problem still occurs: the parent is deleted and the child is orphaned.
    If I execute the very simple example above, I do indeed get an referential constraint error.
    Has anyone ever encountered this situation? And does anyone have any ideas how to go about troubleshooting this problem. We need to know the cause of this, as we have a small handful of table with a similar self-referential foreign key constraint set-up.
    Thank you very much in advance,
    Mark

    First of all, the very simple example that I outlined above I have already tried and it worked: when I attempted to delete the parent a referential integrity error was thrown as one would expect. This small example was my test case to see if I could reproduce what I'm seeing in our application in a more manageable and demonstrable example. But as it worked, I'm still perplexed in reconciling the differences between what I'm seeing in our application (which I can't demonstrate in this help group) and the test case. When I used the test case in my first posting in this thread, I used it to help describe the problem I'm encountered, even though that small example works.
    Below is more of the table you've asked for.
    OWNER           CONSTRAINT_NAME          CONSTRAINT_TYPE     TABLE_NAME     SEARCH_CONDITION     R_OWNER            R_CONSTRAINT_NAME     DELETE_RULE     STATUS          DEFERRABLE            DEFERRED         VALIDATED     GENERATED     BAD     RELY     LAST_CHANGE           INDEX_OWNER  INDEX_NAME       INVALID     VIEW_RELATED
    "DOCPADMIN"     "R_TEMPLATE_PARENT"     "R"             "DCR_TEMPLATE"      (null)                  "DOCPADMIN"     "XPKDCR_TEMPLATE"     "NO ACTION"  "ENABLED"   "NOT DEFERRABLE"    "IMMEDIATE"  "VALIDATED"      "USER NAME"     (null)     (null)     "2010-01-13 19:01:21"     (null)        (null)         (null)       (null)
    "DOCPADMIN"     "XPKDCR_TEMPLATE"       "P"             "DCR_TEMPLATE"      (null)                       (null)     (null)                      (null)          "ENABLED"     "NOT DEFERRABLE"    "IMMEDIATE"      "VALIDATED"     "USER NAME"     (null)     (null)     "2010-01-13 15:48:31"     (null)     "XPKDCR_TEMPLATE"   (null)     (null)Overall, I haven't said that Oracle's FK mechanism is broken. What I've said is that I've got a situation that I'm trying to understand. My first attempt at my test case didn't work because the test case worked as it should. I'm trying to figure out another course of action to try and figure this situation out.

  • 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

  • Re: Foreign key-type constraints

    The methodology my company has defined and uses to attack this problem is
    based upon looking for large grain 'business components' within the
    business model.
    When translating the functionality of the 'business component' to a
    physical design we end up with a component object which usually consists of
    a major entity(table) and several subsidiary entities and the services
    which operate on and maintain those entities i.e. a component object.
    We would then remove the referential integrity constraints only between the
    components - to be managed by a component reference object - but internally
    to the component leave the database referential integrity rules in place.
    I beleive this maintains idea of encapsulation as the only way to
    communicate with the component is through a defined public service
    interface. It also lessens the impact of database changes as they are
    usually confined to one componeet and the public service interface to any
    other is left intact. It makes use of the database functionality without
    dramatically effecting maintenance and performance by writing it all
    yourself and/or defining every relationship with the refence manager.
    It also leads very much to the definition of large grain reusable
    components which can be used in many applications, important to a company
    such as mine which develops software for others.
    Unfortunately it is not always as simple as it sounds, the methodology helps.
    Good database management systems with declarative referential integrity
    will usuaually prevent you from defining circular references so you could
    test for this by attempting to create the database before you remove the
    inter component links. But circular references are much less likely with
    the component technique properly applied.
    Keith Matthews
    Caro System Inc.
    www.carosys.com
    At 02:07 PM 10/23/97 +0100, John Challis wrote:
    We've been pondering the issue of how database integrity should be
    represeted within a Forte/OO app. We're thinking, in particular, about
    foreign key-type constraints.
    First of all, we're not sure whether these constraints should be on the
    database, because some would say that this represents business knowledge
    which should only be in the app. Also, if constraints are on the
    database, the errors you receive if they are violated may not be very
    useful; i.e. we're using Oracle, and we'd have to map constraint names
    in error messages to some more meaningful message to present to a user.
    If foreign key-type constraints aren't on the database, what other
    options do we have?
    Let's say there's associations between objects X, Y and Z, whereby X and
    Y both know about and use Z - we don't want to delete Z while X and Y
    exist. I accept that Z should know how to delete itself, from
    persistance, but how does it check for the existence of X and Y? If Z
    asks objects of types X and Y to check whether they exist in the
    database, you can end up with a circular reference. If you do the check
    yourself, i.e. by having SQL checking existence of X and Y within the
    delete method for Z, then I reckon you've blown encapsulation, and
    you've also got a problem in relation to impact if the shape of your
    database changes.
    We're toying with the idea of having a central integrity manager, which
    will tell Z whether it can go ahead with the delete, thus centralising
    the integrity constraint knowledge within the app. and minimising impact
    of changes to the shape of the database.
    I'd be interested to know what others have done to address this issue,
    and any thoughts you may have.
    Thanks,
    John Challis
    PanCredit
    Leeds, UK
    ** bassssss **

    At 02:07 PM 10/23/97 +0100, you wrote:
    ...>First of all, we're not sure whether these constraints should be on the
    database, because some would say that this represents business knowledge
    which should only be in the app. This is a long-winded response, but I tried to relate it to a real-world
    example, so bear with me...
    Purists may argue with me here, but I must take issue with the notion that
    your database cannot have any business knowledge. As soon as you define a
    table, you have implicitly given the database business knowledge.
    For example, suppose you define a database table Person, with columns Name,
    ID, and BirthDate. You are specifically telling the database that there
    exists a business "something" called Person which can (or must!) have
    values called Name, ID, and Birthdate. You are probably also telling the
    database about certain business rules: The value called ID can be used to
    uniquely identify a Person; The value Name contains text, and has a maximum
    length; Birthdate must conform to the format rules for something of type
    Date; etc. Need I go on?
    So, to me the argument cannot be that your database should not have any
    business knowledge, but rather, what type of business knowledge should be
    given to the database?
    On the other side of the coin, I also take exception to the argument that
    business knowledge belongs only in the Application. In fact, if your
    discussion centers around whether business knowledge belongs in the
    Application vs. the Database, then maybe both sides are still thinking in
    two tiers, and you need to take a step back and think about your business
    classes some more.
    In our oversimplified example above, we set a limit on the length of the
    Name attribute. This is a business rule, and so "belongs" to the business
    class. However, our application class needs to have knowledge of that rule
    so that it can set a limit on the length of data that it allows to be
    entered. Likewise, the persistent storage class must have knowledge of
    that rule to effectively store and retrieve the data.
    We also have an attribute that is a Date, and a date by definition must
    follow certain rules about format and value. The application class and the
    storage class will both do their job more effectively if they know that the
    attribute is a Date.
    Does it break the rules of encapsulation if you allow the application class
    or the storage class to have knowledge of certain rules that are defined in
    the business class? If it does, then we might as well throw encapsulation
    out the door, because it is a totally useless concept in the real world.
    Now, let's think about the referential constraints. Suppose you want to
    create a business class Employee which inherits from the class Person, and
    adds attributes HireDate and Department. When you physically store the
    Employee information in your Relational database, you might actually store
    two tables, with the ID as a foreign key between them. In this case, the
    foreign key relationship would clearly belong to the storage class and the
    database. The business class should not know or care whether the Employee
    information is physically stored in one table, or two, or twelve.
    Now, let's add another business rule, that Employee Department must be a
    valid department. To support this rule, you will create a business Class,
    Department. For the sake of argument, let us say that the persistent data
    for this business class will be stored in a database table, also called
    Department.
    We have said that there is a relationship between Employee and Department.
    Which business class will contain the rule that defines the relationship?
    Clearly, it is not Department. Department has no reason to know about
    Employee, or any other class that might contain a reference to it. Since
    Employee is the one that contains a reference to Department, you could
    argue that the rule belongs there. That works fine, until you want to
    delete a Department object. Obviously, you would not go to the Employee
    class for that. So it seems that the relationship does not belong in
    either class.
    Someone has suggested that you have an integrity manager or some similar
    class for that purpose. The integrity manager would have knowledge of the
    rules that define the relationships between your business objects. This
    allows you to keep your OO design more "pure" from the standpoint of
    encapsulation. Conceptually, this makes good sense, since the relationship
    between two classes does not belong to either of the individual classes.
    Let's hold that thought for a minute.
    Now let's think about your physical database design. I am betting that
    there is a high degree of correlation between your database tables and your
    business objects. It won't be 100%, because, among other things,
    relational databases do not deal well with the concept of inheritance. But
    if there is a very wide divergence, then I would need to question the
    validity of your design. With that in mind, I am going to propose that you
    already have an Integrity Manager, and that is your relational DBMS.
    My position is this, that it is ok, even necessary, for the data storage
    class to have knowledge of the structure and relationships of the data. It
    needs this information to effectively do its job. From my point of view,
    saying that you cannot tell the database that there is a relationship
    between Employee and Department is just as pointless as saying that you
    cannot tell the database that a certain column contains a date, or that
    another column contains a unique key which should be used as an index.
    Would you argue that an index implies business knowledge, and therefore
    does not belong in the database? On the other hand, you could argue that
    referential constraints always belong to the physical storage classes,
    since they describe under what circumstances data can be stored or deleted.
    Now, for performance or other reasons, you might choose not to implement
    the Employee-Department relationship in your physical database, and that's
    ok, too. Maybe you have decided that since you do not delete departments
    very often, that you do not want to incur the database overhead to maintain
    the foreign key relationship. Or maybe you have determined that the
    Department data will be stored somewhere else other than the database.
    Perhaps you would create an Integrity Manager instead, that would only be
    invoked when you wanted to delete a Department object. The point is, if
    you create an Integrity Manager, be sure you do it for the right reason,
    and not because someone has mistakenly decreed that a database cannot have
    any business knowledge.
    This brings us to the other question, which is: What do you do with the
    error if the constraint is violated? Consider this as an option: Create a
    User-defined exception named DeleteFailed or something like that. Then it
    does not matter if the error comes from the database manager or a separate
    Integrity manager. In either case, you fill the exception object with
    whatever meaningful data is appropriate, and raise the exception. The
    application, which knows what it was trying to do, can listen for the
    exception and deal with it appropriately. (btw, this is a good way to deal
    with other predictable database exceptions as well, such as DuplicateKey,
    or NotFound - your application need not listen for a particular SQL Code or
    SQL State, which might tie it to a particular database or storage format.)
    I do not see a problem with using the DBMS to define relational
    constraints. That is, after all, what a Relational database does. You do
    not need an integrity manager for OO-purity, but you can use one if it
    makes sense for other reasons. You should be able to change the method of
    enforcing the relationships, or even change the entire DBMS without having
    any impact on the application classes or the business classes. If you can
    meet that test, then as far as I am concerned, you have not violated any
    rules of encapsulation.
    Any rebuttals?
    =========================================
    Jeanne Hesler <[email protected]>
    MSF&W, Springfield, Illinois
    (217) 698-3535 ext 207
    =========================================

  • Recreating foreign key not working? two proc one to drop constraint and another to recreate foreign constraint in database?

    CREATE PROC [dbo].[SP_DropForeignKeys] 
    AS
    BEGIN
    DECLARE @FKTABLE_OWNER SYSNAME, @FKTABLE_NAME sysname, @FK_Name sysname
    DECLARE Cursor_DisableForeignKey CURSOR FOR  
    SELECT   schema_name(schema_id), object_name(parent_object_id), name
    FROM   sys.foreign_keys
    OPEN Cursor_DisableForeignKey
    FETCH NEXT FROM   Cursor_DisableForeignKey  
    INTO  @FKTABLE_OWNER  , @FKTABLE_NAME, @FK_Name 
    DECLARE @SQL nvarchar(max)
    WHILE @@FETCH_STATUS = 0   
    BEGIN  
    SET @SQL  = 'ALTER TABLE [' + @FKTABLE_OWNER + '].[' + @FKTABLE_NAME   
               + ']  DROP CONSTRAINT [' + @FK_NAME + ']'  
    select @sql
    EXECUTE (@SQL)
    FETCH NEXT FROM   Cursor_DisableForeignKey INTO @FKTABLE_OWNER, @FKTABLE_NAME, @FK_Name
    END  
    CLOSE Cursor_DisableForeignKey
    DEALLOCATE Cursor_DisableForeignKey
    END
    create proc [dbo].[SP_CreateForeignKeys]
    as
    DECLARE @schema_name sysname;
    DECLARE @table_name sysname;
    DECLARE @constraint_name sysname;
    DECLARE @constraint_object_id int;
    DECLARE @referenced_object_name sysname;
    DECLARE @is_disabled bit;
    DECLARE @is_not_for_replication bit;
    DECLARE @is_not_trusted bit;
    DECLARE @delete_referential_action tinyint;
    DECLARE @update_referential_action tinyint;
    DECLARE @tsql nvarchar(4000);
    DECLARE @tsql2 nvarchar(4000);
    DECLARE @fkCol sysname;
    DECLARE @pkCol sysname;
    DECLARE @col1 bit;
    DECLARE @action char(6);
    SET @action = 'CREATE';
    DECLARE FKcursor CURSOR FOR
        select OBJECT_SCHEMA_NAME(parent_object_id)
             , OBJECT_NAME(parent_object_id), name, OBJECT_NAME(referenced_object_id)
             , object_id
             , is_disabled, is_not_for_replication, is_not_trusted
             , delete_referential_action, update_referential_action
        from sys.foreign_keys
        order by 1,2;
    OPEN FKcursor;
    FETCH NEXT FROM FKcursor INTO @schema_name, @table_name, @constraint_name
        , @referenced_object_name, @constraint_object_id
        , @is_disabled, @is_not_for_replication, @is_not_trusted
        , @delete_referential_action, @update_referential_action;
    WHILE @@FETCH_STATUS = 0
    BEGIN
              BEGIN
            SET @tsql = 'ALTER TABLE '
                      + QUOTENAME(@schema_name) + '.' + QUOTENAME(@table_name)
                      + CASE @is_not_trusted
                            WHEN 0 THEN ' WITH CHECK '
                            ELSE ' WITH NOCHECK '
                        END
                      + ' ADD CONSTRAINT ' + QUOTENAME(@constraint_name)
                      + ' FOREIGN KEY ('
            SET @tsql2 = '';
            DECLARE ColumnCursor CURSOR FOR
                select COL_NAME(fk.parent_object_id, fkc.parent_column_id)
                     , COL_NAME(fk.referenced_object_id, fkc.referenced_column_id)
                from sys.foreign_keys fk
                inner join sys.foreign_key_columns fkc
                on fk.object_id = fkc.constraint_object_id
                where fkc.constraint_object_id = @constraint_object_id
                order by fkc.constraint_column_id;
            OPEN ColumnCursor;
            SET @col1 = 1;
            FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
            WHILE @@FETCH_STATUS = 0
            BEGIN
                IF (@col1 = 1)
                    SET @col1 = 0
                ELSE
                BEGIN
                    SET @tsql = @tsql + ',';
                    SET @tsql2 = @tsql2 + ',';
                END;
                SET @tsql = @tsql + QUOTENAME(@fkCol);
                SET @tsql2 = @tsql2 + QUOTENAME(@pkCol);
                FETCH NEXT FROM ColumnCursor INTO @fkCol, @pkCol;
            END;
            CLOSE ColumnCursor;
            DEALLOCATE ColumnCursor;
            SET @tsql = @tsql + ' ) REFERENCES ' + QUOTENAME(@schema_name) + '.' + QUOTENAME(@referenced_object_name)
                      + ' (' + @tsql2 + ')';           
            SET @tsql = @tsql
                      + ' ON UPDATE ' + CASE @update_referential_action
                                            WHEN 0 THEN 'NO ACTION '
                                            WHEN 1 THEN 'CASCADE '
                                            WHEN 2 THEN 'SET NULL '
                                            ELSE 'SET DEFAULT '
                                        END
                      + ' ON DELETE ' + CASE @delete_referential_action
                                            WHEN 0 THEN 'NO ACTION '
                                            WHEN 1 THEN 'CASCADE '
                                            WHEN 2 THEN 'SET NULL '
                                            ELSE 'SET DEFAULT '
                                        END
                      + CASE @is_not_for_replication
                            WHEN 1 THEN ' NOT FOR REPLICATION '
                            ELSE ''
                        END
                      + ';';
            END;
        PRINT @tsql;
        IF @action = 'CREATE'
            BEGIN
            SET @tsql = 'ALTER TABLE '
                      + QUOTENAME(@schema_name) + '.' + QUOTENAME(@table_name)
                      + CASE @is_disabled
                            WHEN 0 THEN ' CHECK '
                            ELSE ' NOCHECK '
                        END
                      + 'CONSTRAINT ' + QUOTENAME(@constraint_name)
                      + ';';
            PRINT @tsql;
            END;
        FETCH NEXT FROM FKcursor INTO @schema_name, @table_name, @constraint_name
            , @referenced_object_name, @constraint_object_id
            , @is_disabled, @is_not_for_replication, @is_not_trusted
            , @delete_referential_action, @update_referential_action;
    END;
    CLOSE FKcursor;
    DEALLOCATE FKcursor;
    GO
    exec [dbo].[SP_DropForeignKeys] 
    exec [dbo].[SP_CreateForeignKeys]
    droped proc worked perfect but when i execute [dbo].[SP_CreateForeignKeys] and try to see again foreign key constraints but result is empty?
    can anybody suggest me what's wrong with these script?

    droped proc worked perfect but when i execute [dbo].[SP_CreateForeignKeys] and try to see again foreign key constraints but result is empty?
    Well, if you have dropped the keys, you have dropped them. They can't be recreated out of the blue. You need to use modify procedure to save the ALTER TABLE statements in a temp table, drop the keys, truncate the tables, and the run a cursor over the
    temp table. In a single transaction, so that you don't lose the keys if the server crashes half-way through.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • 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

Maybe you are looking for

  • Check box in ALV grid gets unselected for new selection

    Hi all, This is my code : TYPE-POOLS : slis. Variable DATA: g_repid LIKE sy-repid,       g_title TYPE lvc_title,       g_set_pf_stat TYPE slis_formname VALUE 'SET_PF_STATUS',       g_user_command TYPE slis_formname VALUE 'USER_COMMAND',       g_layou

  • Printing of Material desc on change of material no in the ADOBE form

    Hi Experts, I want to print material description on change of material no. if there is 4 line item in same matnr then it will show only one desc for this. And on change of matnr it will change and total will print over there. for the 2nd MATNR desc w

  • Idoc/ALE

    Idoc and ALE? What is the use of it in implementation of SAP at what stage?? Best Regards, Deepika

  • Trying to run Ghost blog in https raise errors

    Hi, I'm running my ghost blog in azure, and recently I decided to run it over https. This is my config.js file and web.config. When I run the site in that way the site just show blank page. Those are the supposed right configurations. config.js // ##

  • After updated my Q10 10.2.1.537 the battery always shown 0%

    After updated my Q10 to release 10.2.1.537 the battery always shown 0%, now cannot send out e-mail or dial out call!!! Help pls!!