Primary key  ID ... Foreign key iD ???

Here is the setup. I have a database on a SQL server and have
created a form to input data into this database (with Dreamweaver
and CF).
Let me start out by telling you basically how this data base
is setup:
3 tables:
- tblPatients (which is the main table). Primary key is ID
(an auto number field).
- tblDiagnosis (which only houses an ID field and code field
called DSMIV). The ID in the tblDiagnosis table is a foreign key
and is linked to the tblPatients table’s ID.
-tlkpDiagnosis just house all the possible diagnosis.
I am able to input data into both tblPatients table and the
tblDiagnosis table, BUT the ID (foreign key) field in the
tblDiagnosis table is left empty thus left orphaned with no way to
tight it back to the data in the patient table. My code is below.
Thank you for any help you can provide me.
PROCESS PAGE CODE:
<cfset CurrentPage=GetFileFromPath(GetTemplatePath())>
<cfif IsDefined("FORM.MM_InsertRecord") AND
FORM.MM_InsertRecord EQ "form1">
<cfquery datasource="dsnPsychiatry">
INSERT INTO dbo.tblPatients (NewContinuous, ResidentID,
ResidentInitial, Age, Race, Sex, EmploymentStatus, HP, MedCheck,
Therapy30Minute, Therapy60Minute, TherapyGroup, ECT, Inpatient,
Outpatient, EmergencyRoom)
VALUES (
<cfif IsDefined("FORM.NewContinuous") AND
#FORM.NewContinuous# NEQ "">
<cfqueryparam value="#FORM.NewContinuous#"
cfsqltype="cf_sql_clob" maxlength="1">
<cfelse>
</cfif>
<cfif IsDefined("FORM.ResidentID") AND #FORM.ResidentID#
NEQ "">
<cfqueryparam value="#FORM.ResidentID#"
cfsqltype="cf_sql_clob" maxlength="10">
<cfelse>
</cfif>
<cfif IsDefined("FORM.ResidentInitial") AND
#FORM.ResidentInitial# NEQ "">
<cfqueryparam value="#FORM.ResidentInitial#"
cfsqltype="cf_sql_clob" maxlength="1">
<cfelse>
</cfif>
<cfif IsDefined("FORM.Age") AND #FORM.Age# NEQ "">
<cfqueryparam value="#FORM.Age#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.Race") AND #FORM.Race# NEQ "">
<cfqueryparam value="#FORM.Race#" cfsqltype="cf_sql_clob"
maxlength="1">
<cfelse>
</cfif>
<cfif IsDefined("FORM.Sex") AND #FORM.Sex# NEQ "">
<cfqueryparam value="#FORM.Sex#" cfsqltype="cf_sql_clob"
maxlength="1">
<cfelse>
</cfif>
<cfif IsDefined("FORM.EmploymentStatus") AND
#FORM.EmploymentStatus# NEQ "">
<cfqueryparam value="#FORM.EmploymentStatus#"
cfsqltype="cf_sql_clob" maxlength="10">
<cfelse>
</cfif>
<cfif IsDefined("FORM.HP") AND #FORM.HP# NEQ "">
<cfqueryparam value="#FORM.HP#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.MedCheck") AND #FORM.MedCheck# NEQ
"">
<cfqueryparam value="#FORM.MedCheck#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.Therapy30Minute") AND
#FORM.Therapy30Minute# NEQ "">
<cfqueryparam value="#FORM.Therapy30Minute#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.Therapy60Minute") AND
#FORM.Therapy60Minute# NEQ "">
<cfqueryparam value="#FORM.Therapy60Minute#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.TherapyGroup") AND
#FORM.TherapyGroup# NEQ "">
<cfqueryparam value="#FORM.TherapyGroup#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.ECT") AND #FORM.ECT# NEQ "">
<cfqueryparam value="#FORM.ECT#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.Inpatient") AND #FORM.Inpatient#
NEQ "">
<cfqueryparam value="#FORM.Inpatient#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.Outpatient") AND #FORM.Outpatient#
NEQ "">
<cfqueryparam value="#FORM.Outpatient#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
<cfif IsDefined("FORM.EmergencyRoom") AND
#FORM.EmergencyRoom# NEQ "">
<cfqueryparam value="#FORM.EmergencyRoom#"
cfsqltype="cf_sql_numeric">
<cfelse>
NULL
</cfif>
</cfquery>
<cfloop list="#FORM.DSMIV#" index="diagnosis">
<cfif IsDefined("FORM.DSMIV") AND #FORM.DSMIV# NEQ "">
<cfquery datasource="dsnPsychiatry">
INSERT INTO dbo.tblDiagnosis (DSMIV)
VALUES (
<cfqueryparam value="#diagnosis#" cfsqltype="cf_sql_clob"
maxlength="50">
</cfquery>
</cfif>
</cfloop>
</cfif>

Ok that didn't work. Most likely due to my lack of knowledge
when it comes to this.
I've been doing some research on Stored Prcedures, and
thought it might be the answer to my problems.
Here is the code I came up with.
First is the Stored Procedure (on the SQL Server):
CREATE PROCEDURE spInsertDiagnosis
@ID integer,
@DSMIV varchar(25)
AS
insert into tblDiagnosis (ID, DSMIV) values (@ID, @DSMIV)
GO
Second, is the CF on my process page
<cfif IsDefined ("ID") AND #ID# NEQ "">
<cfif IsDefined("FORM.DSMIV") AND #FORM.DSMIV# NEQ "">
<CFSTOREDPROC procedure="dbo.spInsertDiagnosis"
datasource="dsnPsychiatry">
<CFPROCPARAM type="IN" dbvarname="@ID" value="#ID#"
cfsqltype="CF_SQL_INTEGER">
<CFPROCPARAM type="IN" dbvarname="@DSMIV" value="#DSMIV#"
cfsqltype="CF_SQL_VARCHAR">
</CFSTOREDPROC>
</cfif>
</cfif>
NOTE: The above CF code replaced the below on my process page
(ref to first post).
<cfloop list="#FORM.DSMIV#" index="diagnosis">
<cfif IsDefined("FORM.DSMIV") AND #FORM.DSMIV# NEQ "">
<cfquery datasource="dsnPsychiatry">
INSERT INTO dbo.tblDiagnosis (DSMIV)
VALUES (
<cfqueryparam value="#diagnosis#" cfsqltype="cf_sql_clob"
maxlength="50">
</cfquery>
</cfif>
</cfloop>
PROBLEM now is, in doing this now nothing gets inserted into
the Diagnosis table. Obviously I do not know how to correctly
insert the stored procedure into my process page.

Similar Messages

  • 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

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

  • How to create a primary key or foreign key

    in the table student, sid should be the primary key
    in the table prerequisite cnum should be the foreign key and prereq the primary key
    please help me with the syntax thanks.

    As I said in your other post, it's all in the docs, go first to http://tahiti.oracle.com and try to find the answer yourself
    http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/clauses3a.htm#1002630

  • Mapping in OWB with primary key and foreign key relationship

    Hi all,
    I am new to this datawarehousing field. I have just started my career. I have to now create a mapping in owb where a table has a field which is a primary key of another table in the same staging area. If you guys could help me out with the a method it can be created that would be very helpful to me.
    I thought of 2 ideas,
    1. If I can use a look up, but then I am not sure if i can use a lookup for primary key, foreign key relationship. If I can use also, I do not know how to use that.
    2. What if I can directly take that the first table and link the primary key of that table to the second table which uses that primary key of the first table as one of its fields.
    I do not know how feasible these methods are. Please guys help me out.
    Thanks in advance.

    I have a similar case where table a and table b having relation but table a got inserted with data and table b is empty so there no values for foriegn key column in table b to realte with table a.
    Now i want to load table b foriegn key with primary key column values of table a.
    how can we do this in owb
    thanks
    kumar

  • Primary key and Foreign Key

    Hello,
             I have a question which was asked in an interview
    Can a Primary key in a table also act as a foreign key in the same table ?
    If yes than please provide a simple example
    Thanks
    www.techgulf.blogspot.com

    See this illustration
    create table t
    id int identity(1,1) not null primary key,
    val varchar(100)
    create table t2
    id int not null primary key,
    val varchar(100)
    -- make pk itself as fk to table t
    alter table t2 add constraint fk_t2 foreign key (id) references t(id)
    --some test values to t
    insert t (val)
    values ('test'),('test1'),('test2')
    -- populate t2 first two suceeds
    insert t2(id,val)
    values (1,'iuyi')
    insert t2(id,val)
    values (2,'ef24r')
    -- this will fail as we dont have record with id 4 in t
    insert t2(id,val)
    values (4,'weqw')
    --check the output
    select * from t
    select * from t2
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Primary key and Foreign key on same column

    Hi, I am able to create below tables , primary and foreign keys as below.
    But Is this valid design? Can I define a column (ckey2 in table "child") as
    primary key and as well as foreign key?
    CREATE TABLE parent (
    col1 NUMBER,
    col2 NUMBER
    CREATE TABLE child (
    ckey1 NUMBER,
    ckey2 NUMBER,
    ckey3 NUMBER
    alter table parent add constraint parent_pk primary key( col1 );
    alter table child add constraint child_pk primary key( ckey2 );
    alter table child add constraint child_fk foreign key( ckey2 ) references parent( col1);
    Thanks.

    Can I define a column (ckey2 in table "child") as primary key and as well as foreign key?You mean you want to define a one-to-one relationship between parent and child tables.. why would you want to do that ? You might as well merge the 2 tables into one.

  • Primary Key from foreign keys

    I have a table which has 3 foreign keys, two of which form the primary key.
    I have: ID_Product, ID_Sale, ID_Buy, and also an attribute which tells if its a buy or a sale.
    So, if a sale is made, the primary key should consist of ID_Product && ID_Sale, otherwise, it's ID_Product && ID_Buy.
    Is there a way to do this in Oracle, and if there is, can you point me to where I can read about this?
    thank you in advance

    tashe,
    This is the wrong forum for you question. Try posting here:
    PL/SQL
    I will say, however, that there are advantages to keeping your primary keys apart from your data - just populating them from a sequence. Also, you may be temped to enforce this via triggers, but read the following first:
    http://tkyte.blogspot.com/2008/05/another-of-day.html
    Not that you would have a mutating table problem, but the two table solution may help you. Really think the design through.
    Regards,
    Dan

  • Composite primary key as foreign key not working

    i want have two tables
    in one table i make a composite primary key
    and in the other table i refer one of the column of the composite key from the above table as foreign key in this table but this didn't work.
    eg:
    create table temp1
    ( name char2(10),
    ssn# number(10)
    address varchar2(10)
    constraint (cons_1)primary key(name,ssn#) );
    create table temp2
    ( name1 char2(10) references temp1(name),
    add varchar(20));
    this didn't work....can't create temp2 table it's giving error

    The following includes some corrections and some suggestions. Your original code had several problems: missing comma, invalid name, invalid data type, no unique key for the foreign key to reference. The following fixes all of those and adds some meaningful names for the constraints and formats it so that it is easier to read.
    CREATE TABLE temp1
      (name       VARCHAR2 (10),
       ssn#       NUMBER   (10),
       address    VARCHAR2 (10),
       CONSTRAINT temp1_name_ssn#_pk
                  PRIMARY KEY (name, ssn#),
       CONSTRAINT temp1_name_uk
                  UNIQUE (name))
    Table created.
    CREATE TABLE temp2
      (name1      VARCHAR2 (10),
       address    VARCHAR2 (20),
       CONSTRAINT temp2_name1_fk
                  FOREIGN KEY (name1)
                  REFERENCES temp1 (name))
    Table created.

  • Primary keys and foreign keys

    Hi,
    is there a script available for changing the value of a primary key which automaticly
    detect all foreigs keys refering to this primary key and change them as well?
    William Oorschot

    I don't have the script now. but you can make a procedure of ur own.
    using a join on user_constraints, and user_cons_columns you can find out all the columns in all the tables which are referencing the particular primary key. once you have the table and the referencing columns, you can change the value of those columns with the new value.
    you'll have to call this procedure from a before row level trigger.
    HTH
    Naveen

  • ODI not able to detect primary/foreign keys from XML- user lacks privilege or object not found

    Hi Guys,
    Im trying to load an xml file with two entities address and employee as below. The topology reverse engineering everything works fine. Im even able to view the xml data  in ODI,  but when i try to load the data from these two entities joining by the schema primary keys and foreign keys which odi created on reverse engineering process for xml, im getting the below error.  Im able to load data from one entity, error only occurs when i use the join odi creates internally to identify the xml components employee and address
    XML File:
    <?xml version="1.0" encoding="UTF-8" ?>
    <EMP>
    <Empsch>
    <Employee>
    <EmployeeID>12345</EmployeeID>
    <Initials>t</Initials>
    <LastName>john</LastName>
    <FirstName>doe</FirstName>
    </Employee>
    <Address>
    <WorkPhone>12345</WorkPhone>
    <WorkAddress>Test 234</WorkAddress>
    </Address>
    </Empsch>
    </EMP>
    Topology:  jdbc:snps:xml?f=C:/Temp/RR/Empsch.xml&s=Empsch&re=EMP&dod=true&nobu=false
    Error Message:
    -5501 : 42501 : java.sql.SQLException: user lacks privilege or object not found: EMPSCH.EMPSCHPK
    java.sql.SQLException: user lacks privilege or object not found: EMPSCH.EMPSCHPK
        at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
        at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
        at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
        at com.sunopsis.jdbc.driver.xml.SnpsXmlConnection.prepareStatement(SnpsXmlConnection.java:1232)
        at sun.reflect.GeneratedMethodAccessor65.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at oracle.odi.core.datasource.dwgobject.support.OnConnectOnDisconnectDataSourceAdapter$OnDisconnectCommandExecutionHandler.invoke(OnConnectOnDisconnectDataSourceAdapter.java:200)
        at $Proxy2.prepareStatement(Unknown Source)
        at oracle.odi.runtime.agent.execution.sql.SQLCommand.doInitializeStatement(SQLCommand.java:83)
        at oracle.odi.runtime.agent.execution.sql.SQLCommand.getStatement(SQLCommand.java:117)
        at oracle.odi.runtime.agent.execution.sql.SQLCommand.getStatement(SQLCommand.java:111)
        at oracle.odi.runtime.agent.execution.sql.SQLDataProvider.readData(SQLDataProvider.java:81)
        at oracle.odi.runtime.agent.execution.sql.SQLDataProvider.readData(SQLDataProvider.java:1)
        at oracle.odi.runtime.agent.execution.DataMovementTaskExecutionHandler.handleTask(DataMovementTaskExecutionHandler.java:70)
        at com.sunopsis.dwg.dbobj.SnpSessTaskSql.processTask(SnpSessTaskSql.java:2913)
        at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java:2625)
        at com.sunopsis.dwg.dbobj.SnpSessStep.treatAttachedTasks(SnpSessStep.java:577)
        at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java:468)
        at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java:2128)
        at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor$2.doAction(StartSessRequestProcessor.java:366)
        at oracle.odi.core.persistence.dwgobject.DwgObjectTemplate.execute(DwgObjectTemplate.java:216)
        at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor.doProcessStartSessTask(StartSessRequestProcessor.java:300)
        at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor.access$0(StartSessRequestProcessor.java:292)
        at oracle.odi.runtime.agent.processor.impl.StartSessRequestProcessor$StartSessTask.doExecute(StartSessRequestProcessor.java:855)
        at oracle.odi.runtime.agent.processor.task.AgentTask.execute(AgentTask.java:126)
        at oracle.odi.runtime.agent.support.DefaultAgentTaskExecutor$2.run(DefaultAgentTaskExecutor.java:82)
        at java.lang.Thread.run(Thread.java:662)
    Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: EMPSCH.EMPSCHPK
        at org.hsqldb.error.Error.error(Unknown Source)
        at org.hsqldb.ExpressionColumn.checkColumnsResolved(Unknown Source)
        at org.hsqldb.QueryExpression.resolve(Unknown Source)
        at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
        at org.hsqldb.ParserCommand.compilePart(Unknown Source)
        at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
        at org.hsqldb.Session.compileStatement(Unknown Source)
        at org.hsqldb.StatementManager.compile(Unknown Source)
        at org.hsqldb.Session.execute(Unknown Source)
        ... 27 more
    Please advice
    Thanks
    Revanth

    Thats obvious from the xml file contents you have given here. In this xml file You have four complex type. Two of them are employee and address. However the employee doesnot have any relation with address as you have not added the relationship. Thats why its failing. Its not the fault of ODI.
    Also I would suggest not to use auto generated dtd by ODI as you might face problem in future. For example the address type of XML has 8 attributes and 4 of them are not mandatory. That means each of your xml file may have attributes between 4 to 8.  This is where ODI auto generated DTD fails.
    XML Schema complexType Element
    Thanks
    Bhabani

  • Primary&foreign key rerlation ship

    hi folks,
    i am going to pick material in mm03 transaction after that i selected  classification tab choose batches for class type it displays values and clisifications
    now i want to find tables which is having the relation ship (primary key and foreign key)between material number and class type
    so could plz clarify my doubt
    regards,
    sree

    Hi
    Check table DD05S.
    Award points if found useful.
    Regards
    Inder

  • Update primary key that’s also a foreign key in another table

    Hi Developers,
    I need to update the primary key for a record but it's also the foreign key in another table.
    Example,
    Table 1 Details
    Name : Parent_Table
    Columns : ID, Name, Age
    Primary Key : ID
    Table 2 Details
    Name : Child_Table
    Columns : ID, Parent_ID, Name, Age
    Primary Key : ID
    Foreign Key : Parent_ID (Primary Key in Parent_Table)
    Parent_Table
    ID Name Age
    1001 Sam 26
    1002 George 25
    Child_Table
    ID Parent_ID Name Age
    1010 1001 Sam 26
    1020 1002 George 25
    Now I want to update ID (1001) in Parent_table as 2001 and also, I want to update Parent_ID (1001) in Child_Table as 2001.
    How we will write the java code to update these columns.
    Thanks in advance.

    dcminter wrote:
    If you're looking at changing the primary keys in your data then there's probably something wrong with your data structure.Depends how you feel about business primary keys versus surrogates. Personally I prefer the latter so I'm with you in theory. In practice, however, a DB that uses a business PK may well find that it's a legitimate use case to change the key value (but then that's why I like surrogates in the first place!)Primary keys should not have meaning.

  • Binding for table produces list for other tables using foreign key and crea

    Using
    software Jdev 11G, WLS 11G, Oracle DB 11G, Windows Vista platform
    technology EJB 3.0, jspx, backing beans, session bean
    I cannot create a namedquery on my secondary table. The method for the column uses the entity object rather than the name and value of the column.
    For instance,
    (Coketruck) table has inventory records(Products) table
    Coketruck has one to many to the Products table
    Products has a many to one to the Coketruck
    I need to return the products from the product table based on the CokeTruck but I cannot create a namedQuery because the method in the Product table is an entity object type instead of a long that I can use to look up all the products based off the column truck_id.
    This is what I was expecting…
    Private Long truckId;
    public Long getTruckId() {
    return truckId;
    public void setTruckId (Long truckId) {
    this. truckId = truckId;
    Instead this is what I have…
    @ManyToOne
    @JoinColumn(name = "TRUCK_ID")
    private Coketruck coketruck;
    this. coketruck = coketruck
    public Coketruck getCoketruck() {
    return coketruck;
    public void set Coketruck (Coketruck coketruck) {
    this. coketruck = coketruck;
    How do I do a query on the Product table to return all the products that are in the coketruck?
    If I do the following it expects for me to pass the Entity Object which I cannot use as search criteria for my find method.
    @NamedQuery(name = "Products.findById", query = "select o from Products o where o.truckId = :truckId")
    On a different note but the same song…
    I noticed that when I look at my Session Bean Data Contols that the coketruck already has a list of the products. I have created a jsp page with a backing bean and have been able to use the namedquery on the coketruck entity to retrieve the productList. Unfortunately I need to sort the products by type and was also not able to find where to perform the work to be able to iterate through the productList to get my desired display. Therefore I started looking at doing another namedquery that would only retrieve the product_type ordering by the truckId.
    Seems I have come full circle… I don’t care what method I have to use to get the info back.
    Any help is greatly appreciated!

    user9005175 wrote:
    Hi!
    I work on an application wich uses a shopping cart stored in a database. The shopping cart uses two tables:
    CART: Holds information common for one shopping cart: the user it is connected to etc.
    - Primary key: CART_ID
    CART_ROW: One row in the cart, e.g. one new product to buy.
    - Primary key: ROW_ID
    - Foreign key: CART_ROW.CART_ID references CART.CART_ID
    From the code the rows in the cart are collected per cart, as is modelled by the foreign key. There exists one more relationship, which we use in the code, but which is not modelled by a foreign key in the database. One row can be dependent on another row, which makes the other row a parent.
    CART_ROW has a column PARENT_ID which references CART_ROW.ROW_ID.
    Should we add a foreign key for PARENT_ID? Or are there any questions to consider when it is a foreign key to the same table?
    I suggest to add foreign key it wont harm the performance (except while on insert when there would be validation for the foreign key). But it would prevent users to insert wrong/corrupt data either through code or directly by loggin in the database.
    A while ago we added indexes, both on ROW_ID and on PARENT_ID. Could the index on PARENT_ID have been harmful, since there is no foreign key?
    Index on parent_id would only be harmful if you do not make use of index after creating it (i.e. there is no query which make use of this index).
    And if you decide to have a foreign key on parent_id then I suggest to have index too on parent_id as it would be helpful atleast when you delete any record in this table.
    Best regards!

  • Foreign key errors in sql plus

    Hello, im pretty new to sql and i am stuck on a project in my database management class and i was wondering if anyone can help us out. I don't know if it would be easier to send what i've done or just post the error so if anyone could help it will be appreciated.
    This is one part of the sql
    CREATE TABLE PREREQUISITE_T
         (COURSECODE                VARCHAR2(10)NOT NULL,
         PREREQUISITECODE          VARCHAR2(20),
    PRIMARY KEY (COURSECODE),
    PRIMARY KEY (PREREQUISITECODE),
    FOREIGN KEY (COURSECODE) REFERENCES COURSE_T(COURSECODE),
    FOREIGN KEY (PREREQUISITECODE));
    INSERT INTO PREREQUISITE_T VALUES ('23131', '3213');
    INSERT INTO PREREQUISITE_T VALUES ('23541', '4213');
    INSERT INTO PREREQUISITE_T VALUES ('23251', '3413');
    INSERT INTO PREREQUISITE_T VALUES ('56131', '3513');
    INSERT INTO PREREQUISITE_T VALUES ('75431', '3613');
    INSERT INTO PREREQUISITE_T VALUES ('45631', '3813');
    INSERT INTO PREREQUISITE_T VALUES ('65461', '3913');
    INSERT INTO PREREQUISITE_T VALUES ('45351', '5413');
    the error i get is
    ERROR at line 1:
    ORA-02298: cannot validate (STUDENT.SYS_C003016) - parent keys not found
    It works fine without the primary keys but when i put in foreign keys it is all messed up. If there a a tutorial or anyone could take a look at the rest of the code i can send it out. Any help is appreciated.

    probably u had given the column value not exists in the reference table.
    see the example
    create table tst(x number ,y number);
    alter table tst add constraints pk_x primary key(x);
    create table tst1(x number, y number);
    alter table tst1 add constraints fk_x foreign key(x) references tst(x);
    SQL> insert into tst values(&x,&y);
    Enter value for x: 1
    Enter value for y: 2
    old 1: insert into tst values(&x,&y)
    new 1: insert into tst values(1,2)
    1 row created.
    SQL> /
    Enter value for x: 2
    Enter value for y: 3
    old 1: insert into tst values(&x,&y)
    new 1: insert into tst values(2,3)
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> insert into tst1 values(&x,&y);
    Enter value for x: 2
    Enter value for y: 1
    old 1: insert into tst1 values(&x,&y)
    new 1: insert into tst1 values(2,1)
    1 row created.
    SQL> /
    Enter value for x: 5
    Enter value for y: 6
    old 1: insert into tst1 values(&x,&y)
    new 1: insert into tst1 values(5,6)
    insert into tst1 values(5,6)
    ERROR at line 1:
    ORA-02291: integrity constraint (SHFLDEV.FK_X) violated - parent key not found

  • Find foreign key which are able or not

    Same as the topic ~ how can I find all the able/unable foreign key/contraints inside a database ? Using TSQL

    Hello,
    Please try the scripts provided on the following resources:
    http://blog.sqlauthority.com/2009/07/17/sql-server-two-methods-to-retrieve-list-of-primary-keys-and-foreign-keys-of-database/
    http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/
    http://blog.sqlauthority.com/2007/09/16/sql-server-2005-list-all-the-constraint-of-database-find-primary-key-and-foreign-key-constraint-in-database/
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

Maybe you are looking for