A quesion about FOREIGN KEY

Hi,
I know how to add one foreign key on a table,but don't know how to add two foreign keys at a time.
The following codes have errors,somebody cound tell me how to amend it ?
Many thanks
ALTER TABLE A ADD CONSTRAINT a_fk
FOREIGN KEY (b) REFERENCES B(b),
FOREIGN KEY (c) REFERENCES C(c);

Hi,
about foreign keys
http://www.techonthenet.com/oracle/foreign_keys/foreign_keys.php
http://www.psoug.org/reference/constraints.html
Regards,
Max.

Similar Messages

  • Urgent expalantion reqired about foreign keys

    we are doing data migration project and we have get data from different regions data in flat files, but we have problem below like:
    i am facing a problem to declare unique constraints, because in some files column should be in number data type and same file from some other region is varchar2 but these two columns are unique ,these two columns don't having the any duplicate values.
    can i take this column data type in varchar2?
    why because if i am taking number type it cant accept varchar2
    any suggestions.................
    Regards,
    sh

    sh wrote:
    we are doing data migration project and we have get data from different regions data in flat files, but we have problem below like:
    i am facing a problem to declare unique constraints, because in some files column should be in number data type and same file from some other region is varchar2 but these two columns are unique ,these two columns don't having the any duplicate values.
    can i take this column data type in varchar2?
    why because if i am taking number type it cant accept varchar2
    any suggestions.................
    Regards,
    shNot really sure i understand your question. If you have 2 data sources and 2 different data types for the same type of data then you'd want to ensure you do a TO_NUMBER on the character representation of the data to ensure you strip out any non-printing characters like tabs or spaces.
    If that's not your problem, please try to be a little more clear. Your subject mentions you have an urgent problem about foreign keys and i find nothing to support your claim of urgency, nor foreign keys, within the subject of your question.
    Cheers,

  • A question about foreign key to multiple tables

    Hello everybody,
    I have a question about creating foreign key and I would appreciate if you could kindly give me a hand. Here are my tables:
    CREATE TABLE TEAM1(team_id VARCHAR2(20), project_id VARCHAR2(20));
    ALTER TABLE TEAM1 ADD CONSTRAINT PK_TEAM1 PRIMARY KEY(team_id);
    CREATE TABLE TEAM2(team_id VARCHAR2(20), project_id VARCHAR2(20));
    ALTER TABLE TEAM2 ADD CONSTRAINT PK_TEAM2 PRIMARY KEY(team_id);although the structure of both the tables is exactly the same, the values (in particular team_id) in both tables are different.
    Also I have another table named AGENT
    CREATE TABLE AGENT(agent_id VARCHAR2(20), team_id VARCHAR2(20));
    ALTER TABLE AGENT ADD CONSTRAINT PK_AGENT PRIMARY KEY(agent_id)Now the problem is that the column team_id in AGENT table is actually a foreign key, but the value can be in either TEAM1 or TEAM2. As far as I know a foreign key points only to one table.
    How can I deal with this problem? Whenever there is an INSERT or UPDATE I have to make sure that the value of the column "team_id" in the table "AGENT" is a valid value either in "TEAM1" or "TEAM2"
    Thanks in advance,
    Kind Regards,
    Dariyoosh

    Do you have the ability to change the data model? If so a more appropriate structure may be something like this:
    CREATE TABLE TEAM(team_id VARCHAR2(20), team_name VARCHAR2(20));
    ALTER TABLE TEAM ADD CONSTRAINT PK_TEAM PRIMARY KEY(team_id);
    ALTER TABLE TEAM ADD CONSTRAINT UK_TEAM UNIQUE (team_name);
    CREATE TABLE TEAM_PROJECT(team_id VARCHAR2(20), project_id VARCHAR2(20));
    ALTER TABLE TEAM ADD CONSTRAINT PK_TEAM_PROJECT PRIMARY KEY(team_id, project_id);
    ALTER TABLE AGENT ADD CONSTRAINT FK_TEAM_PROJECT1 FOREIGN KEY (team_id) REFERENCES TEAM(team_id);
    CREATE TABLE AGENT(agent_id VARCHAR2(20), team_id VARCHAR2(20));
    ALTER TABLE AGENT ADD CONSTRAINT PK_AGENT PRIMARY KEY(agent_id);
    ALTER TABLE AGENT ADD CONSTRAINT FK_TEAM FOREIGN KEY (team_id) REFERENCES TEAM(team_id);Edited by: Centinul on Jun 25, 2010 10:50 AM

  • Foreign key dependency checking

    Dear all:
    I have a question about foreign key checking.
    Let's say I have two Z table, one is master table and one is transaction table.
    The master table contains a primary key named CustNo.
    The transaction table have two primary keys named CustNo and OrderNo.
    The CustNo has foreign key (mandt + CustNo) point to master table, with setting
    "Key fields/candidates  1:N"
    I expected that, delete record in master table should check if there is any dependency in the transaction table,
    but I am wrong.  I am able to delete anything in master table even there are records in transaction table using the same CustNo.
    My question is, how can I make the dependency check?
    Thanks in advance.
    Edited by: Hung Kai, Michael Cheng on Nov 3, 2008 5:29 AM

    Hello,
        For this u need to change the cardinality.
    Below are the list of cardinalities and their functionality.Chack it and use the proper one.
    The left side (n) of the cardinality is defined as follows:
    n=1: There is exactly one record assigned to the check table for each record of the foreign key table.
    n=C: The foreign key table may contain records which do not correspond to any record of the check table because the foreign key field is empty. This can occur for example if the field of the foreign key table is optional, in which case it does not have to be filled.
    The right side (m) of the cardinality is defined as follows:
    m=1: There is exactly one dependent record for each record of the check table.
    m=C: There is at most one dependent record for each record of the check table.
    m=N: There is at least one dependent record for each record of the check table.
    m=CN: There may be any number of dependent records for each record of the check table.
    Shafi

  • How to transfer database table contain null values, primary key, and foreign key to the another database in same server. using INSERT method.

    how to transfer database table contain null values, primary key, and foreign key to the another database in same server. using INSERT method.  thanks

    INSERT targetdb.dbo.tbl (col1, col2, col3, ...)
       SELECT col1, col2, col3, ...
       FROM   sourcedb.dbo.tbl
    Or what is your question really about? Since you talke about foreign keys etc, I suspect that you want to transfer the entire table definition, but you cannot do that with an INSERT statement.
    Erland Sommarskog, SQL Server MVP, [email protected]

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

  • Foreign key changing name...

    Hi again, and again...! (at least I always punch the helpful and correct buttons ...:P)
    Clearly, I lack knowledge about foreign keys.
    Of course I searched the web before posting.
    !http://img264.imageshack.us/img264/9602/dsdv.png!
    This is the strange DSD...
    The Team table (equipe) is connected to Rencontre (Meeting)
    During a meeting (NoR 1,2 ... incrementation), there is TWO teams : NoEH (Host team) and NoEV (Visiting team)... these are FK for NoE (Team number)
    This is so strange...
    The Partie (Match) occurs from 3 to 5 times during a Meeting, and the winner is put on the H_ or V_, which only says which team wins... visiting or host
    How am I suppose to make a select table stating which team (NoE!!!! not NoeH! or NoeV?!!) won how many games, how many games played, wtc...
    Anyone know a tactic to approach this problem?
    I was thinking of maybe creating a view for each team to add their wins...?

    Hi,
    For this case can you post scripts for creation of tables and a minimal data? And also please post the specific problem you are having.
    Regards,

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

  • Basic doubt about Primary Key/Foreign Key in Oracle Tables

    Hi,
    I have a doubt whether Primary Keys/Foreign Keys are allowed in Oracle. Some of the people I know are telling me that Oracle does not encourage having Primary Keys/Foreign keys in its database tables.
    However if I go to the ETRM and look for information about some of the Oracle Tables, I am informed that Primary Keys do exist. However I am being told that ETRM is not a reliable way of having correct information about table structure.
    It would be great if any one of you provides me with some insight in this. Any pointers to a document would be great.
    Thanks

    It is not that PK/FKs are disallowed in Oracle Apps (there are some on the standard Oracle Apps tables), but they are typically not used. I am not positive what the logic behind this is, but my guess is that it was party due to the earlier versions of Oracle Apps pre-dating declarative database referential integrity in Oracle DB and also on performance issues with the standard referential integrity with the earlier versions of declarative database referential integrity.
    As far as eTRM is concerned - I understood that the data is based on a design repository rather than a physical Oracle Apps DB. So all of the information in there is logically correct, but not necessarily enforced via the standard Oracle DB declarative referential integrity (rather by the application code or APIs).

  • Basic doubt about Primary Keys/Foreign Keys in Oracle Tables

    Hi,
    I have a doubt whether Primary Keys/Foreign Keys are allowed in Oracle or not. I have been informed that Oracle does not encourage having Primary Keys/Foreign keys in its database tables. Instead it urges users to have unique constraints on the requisite columns.
    However if I go to the ETRM and look for information about some of the Oracle Tables, I am informed that Primary Keys do exist. At the same time, I am being told that ETRM is not a reliable way of having correct information about table structure (at least the Primary Key information).
    It would be nice if any one of you provides me with some insight in this. Any pointers to a document would be welcome.
    Thanks

    FYI,
    There is seprate forum for Core Sql quieries
    PL/SQL
    Thanks

  • Question about scripting of foreign keys

    When I script FK_SalesOrderHeader_Address_BillToAddressID key from AdventureWorks.[Sales].[SalesOrderHeader] I get this:
    ALTER TABLE [Sales].[SalesOrderHeader] WITH CHECK ADD CONSTRAINT [FK_SalesOrderHeader_Address_BillToAddressID] FOREIGN KEY([BillToAddressID])
    REFERENCES [Person].[Address] ([AddressID])
    GO
    ALTER TABLE [Sales].[SalesOrderHeader] CHECK CONSTRAINT [FK_SalesOrderHeader_Address_BillToAddressID]
    GO
    EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Foreign key constraint referencing Address.AddressID.' , @level0type=N'SCHEMA',@level0name=N'Sales', @level1type=N'TABLE',@level1name=N'SalesOrderHeader', @level2type=N'CONSTRAINT',@level2name=N'FK_SalesOrderHeader_Address_BillToAddressID'
    GO
    What is second ALTER statement for (the one highlighted with bold font)? First ALTER statement already includes WITH CHECK, so isn't the second one redundant?

    The 2nd Statement enables the Foreign Key.
    I think it is redundant because FOREIGN KEY is enabled by default when you execute the 1st statement.
    This script is generated by SSMS (Yes?), This is added just to ensure that CONSTRAINT is enabled.
    - Vishal
    SqlAndMe.com
    Yes, it is generated by SSMS 2008.

  • 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

  • Can we associate index with foreign key?

    hello
    i have searched and could not find the answer to the above;
    i have a foreign key constraint on the tables; i added an index on that column as well;
    however when i query the all_constraints, under index_name for this foreign constraint there is nothing; only when i have PK/UK i case see indexes associated with them;
    will then oracle still associate my index with the FK constrained column? or i need to excplicity associate it with the foreign key column? if so, how to do that?
    thx
    rgds

    Hi,
    UserMB wrote:
    i have a foreign key constraint on the tables; i added an index on that column as well;It helps if you give a specific example, such as:
    "I have a foreign key constraint, where emp.deptno references dept.deptno. (Deptno is the primary key of dept.) I created an index called emp_deptno_idx on emp.deptno as well."
    however when i query the all_constraints, under index_name for this foreign constraint there is nothing; only when i have PK/UK i case see indexes associated with them;Not all indexes are associated with a constraint. In the example above, you wouldn't expect to see anything about the index emp_demptno_idx in all_constraints or in all_cons_columns.
    will then oracle still associate my index with the FK constrained column? or i need to excplicity associate it with the foreign key column? if so, how to do that?In the situation above, Oracle will still use the index when the optimizer thinks it will help. You don't have to do anything else.

  • Subquery in IF statement in trigger, without using foreign keys

    Hello,
    I'm investigating ways of writing a subquery in an IF statement, which is placed inside a trigger.
    I wanna write smth like IF (:new.jazz not in (select goldies from T where ... )) etc. I don't know whether the fact that the IF is in a trigger adds some additional restrictions. (Does it?)
    So far I found the solution described here: SubQuery Comparison in If Statement which I find a bit tacky, I could have the 'cooleststarinthegalaxy' instead of 1 and seems you need to do extra light, but still extra lifting.
    I also read about the possibility of using MERGE, which I'm currently researching.
    Is there any other way?
    Thanks
    Edited by: BluShadow on 14-Nov-2012 13:37
    fixed link
    Edite by me: the question is how (if possible) to do this without a foreign key.
    Edited by: questioningq12 on Nov 14, 2012 6:11 AM
    Edited by: questioningq12 on Nov 14, 2012 6:13 AM

    Hi,
    questioningq12 wrote:
    Say I have tables A(namea varchar(10)), B(nameb varchar(10)), and B contains tuples ('1stname','2ndname').
    I wrote a trigger before insertion, for each row, on table A. For a tuple t to be inserted, it should check whether t.namea is in the set of values nameb from B.
    E.g., INSERT INTO A VALUES('1stname') should work. But INSERT INTO A VALUES ('3rdname') should fail. You can use a foreign key constraint for that.
    If the tables already exist, and b.nameb is declared as UNIQUE (or PRIMARY KEY), then you can say:
    ALTER TABLE  a
        ADD CONSTRAINT     a_namea_fk
        FOREIGN KEY  (namea)
        REFERENCES b (nameb)
    ;If you had a situation where you really needed to query a table in PL/SQL, and you weren't sure if the query would find anything, you could put the query in its own BEGIN ... EXCEPTION block, and test for NO_DATA_FOUND.
    If you're just checking to see if a row exists or not, you can always write a query that is guaranteed to return exactly 1 row, like this:
    BEGIN
        SELECT  COUNT (*)
        INTO    x
        FROM    b
        WHERE   nameb = :NEW.namea
        AND         ROWNUM  = 1;
        IF x = 0
        THEN  
            ...        -- print msgs, raise exceptions etc
        END IF;
    END;Edited by: Frank Kulash on Nov 14, 2012 9:22 AM
    Added example

  • How to create a foreign key for the table from two different tables?

    Hi All,
    I have a three table like below. In the below table SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK will be having the primary key for NAME column. The same SAMPLE_CONS3_CHECK table also having the primary key for NAME column and forieign key for SAMPLE_CONS_CHECK and SAMPLE_CONS2_CHECK tables. See the below code 2
    code 1:
    CREATE TABLE SAMPLE_CONS_CHECK
            (NAME VARCHAR2(10),
            SERIES  VARCHAR2(5)
    CREATE TABLE SAMPLE_CONS2_CHECK
            (NAME  VARCHAR2(5),
             MODEL  NUMBER
    CREATE TABLE SAMPLE_CONS3_CHECK
            (NAME  VARCHAR2(5),
             MODEL_NO  NUMBER
            )code 2
    alter table SAMPLE_CONS_CHECK
    add constraint SAMPLE_CONS_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS2_CHECK
    add constraint SAMPLE_CONS2_CHECK_pk primary key (NAME)
    alter table SAMPLE_CONS3_CHECK
    add constraint SAMPLE_CONS3_CHECK_pk primary key (NAME)
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK1 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS_CHECK
        NAME
    ) ON DELETE CASCADE;
    ALTER TABLE SAMPLE_CONS3_CHECK ADD
    CONSTRAINT SAMPLE_CONS3_CHECK_FK2 FOREIGN KEY
         NAME
    ) REFERENCES SAMPLE_CONS2_CHECK
        NAME
    ) ON DELETE CASCADE;From the above schenario i am able to insert the data to SAMPLE_CONS3_CHECK table. But the parent data is already available in the parent table. The problem is here two different constarints from two different tables. While inserting, it is checking from both the tables whether the parent is exist or not.
    How can i solve this problem? Can anyone halp me about this?
    Thanks
    Edited by: orasuriya on Aug 8, 2009 2:02 AM

    Actually the design is completely incorrect.
    What you say is
    I have
    'foo', 'foo series'
    'foo','foo model'
    'foo',666
    By virtue of table3 referring to both table1 and table2.
    This means you actually need to have 1 (one) table:
    'foo','foo series','foo model', 666
    And the 'problem' disappears.
    Sybrand Bakker
    Senior Oracle DBA

Maybe you are looking for