Optional Composite Foreign Key
The tool doesn't seem to be handling this correctly when some of the columns are mandatory and others are nullable. I have a composite foreign key where one column is part of the primary key and the other is not. In the Columns properties of the Table dialog, it shows the column that is part of the primary key as mandatory. But on the diagram, the "red dot" indicator is missing. It also give me an error on the Foreign Keys properties when I click OK or Apply.
No, You cant get a composite keys based on two different primary keys. Reason for this can be like unique index is being used when we create any primary key. When we create a composite primary key, one index is created for the two fields and thus one index store the values for two columns involved in the composite primary key and these values are stored in pairs. So when any foreign key references this composite primary key, it will match the data in pairs as it is stored in the index(unique index).
Now when we say to create a composite foreign key based on two different primary keys , we are taking into account two indexes for two different fields. So there is no pairing in these two indexes. So when we will create foreign key using this, it will not get a pair of values or we can say oracle cant get us consistent pair of values from two indexes. So maintaining integrity will not be possible.
Yes you can create two foreign keys on one column which can refer two different primary keys.
Regards
Similar Messages
-
How do I map a composite foreign key using toplink?
I can reference a particular record in mytable using the following sql statement:
SELECT * FROM mytable m WHERE m.foreign_id = x AND m.type = y;
Where x represents the primary key in my entity and y represents a second part of the primary key (e.g. "type 1")
How do I accomplish this from within my entity?
ThanksIf you are using JPA, you need to use either an IdClass or EmbeddedId for composite primary keys.
If you are using the TopLink native API you just need to call addPrimaryKeyFieldName() with both column names.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Composite_Primary_Keys
James : http://www.eclipselink.org -
Composite Foreign Key Relationships
I'm having problems defining relationships that are using the same set of fields in a composite primary key and a composite foreign key. Are there any examples for doing this kind of thing. I think I have the primary keys set up correctly but the foreign key defs aren't working yet. From the spec it looks ike it should be something like this:
@ManyToOne
@PrimaryKeyJoinColumns({
@PrimaryKeyJoinColumn(name="CGMTI_ID"),
@PrimaryKeyJoinColumn(name="MISSION_REF_DATE")})
CgmtiHeader cgmtiHeader;
Also, the composite foreign keys seem to make Dali's entity generation blow up.This mapping is missing the referencedcolumn definition, and because it is a composite pk, it cannot figure out a default value. So it should similar to:
@ManyToOne
@PrimaryKeyJoinColumns({
@PrimaryKeyJoinColumn(name="CGMTI_ID", referencedColumnName="CGMTI_ID),
@PrimaryKeyJoinColumn(name="MISSION_REF_DATE", referencedColumnName="MISSION_REF_DATE)})
CgmtiHeader cgmtiHeader;
Similar discussions exist in threads:
Extra Columns in ManyToMany table workaround
and
http://forums.java.net/jive/thread.jspa?threadID=2564&messageID=36441
both of which list blogs showing examples.
Best Regards,
Chris -
Dear All
please correct this syntax for composite foreign key.
Ater Table emp_pays
Add Constraints emp_pt_fk Foreign Key(emp_id,pt_id) Referenes emp(emp_id),pay_type(pt_id);
Thanks in advances
Regards,No, You cant get a composite keys based on two different primary keys. Reason for this can be like unique index is being used when we create any primary key. When we create a composite primary key, one index is created for the two fields and thus one index store the values for two columns involved in the composite primary key and these values are stored in pairs. So when any foreign key references this composite primary key, it will match the data in pairs as it is stored in the index(unique index).
Now when we say to create a composite foreign key based on two different primary keys , we are taking into account two indexes for two different fields. So there is no pairing in these two indexes. So when we will create foreign key using this, it will not get a pair of values or we can say oracle cant get us consistent pair of values from two indexes. So maintaining integrity will not be possible.
Yes you can create two foreign keys on one column which can refer two different primary keys.
Regards -
Composite foreign key, LOV, WSG, Designer 6i
Hello,
I have one composite foreign key that consists of 3 columns,
which belongs to three different tables (there are
master-detal-detail relationships between those 3 tables). Let's
call those tables A, B and C.
Now, I'd like to generate wsg module (based on table D) that has
all three columns displayed. Also, I'd like to generate three
dependant LOVs in such way that I am able first to select row
from table A using first LOV. Second LOV should display rows from
table B, but only those rows that are in context of A. Similary,
third LOV should display rows from table C, but only rows in
context of B.
Is there any way to this in Designer 6i Release 4 ? This way
default behaviour in Designer 2.1.2 and 6.
Thanks.
Goran Oparnica
IN2 d.o.o.
ZagrebThe Headstart Utilities are part of the Headstart Oracle Designer package which is downloadable from OTN. Headstart Oracle Designer is an accelerator suite consisting of Templates, Object Libraries, Preference Sets, PL/SQL libraries and utilities to make using Designer to generate Forms applications easier.
To get more information on Headstart you can go to the OTN home page, choose Internet Tool under the Products section on the menu. Under the Headstart 'Internet Developer Suite', click on Headstart Oracle Designer
Regards,
Lauri -
Need help with defining composite foreign keys
Hi there, i´m in troubles with defining a composite foreign key. The scenario is:
* Table TABLE_A has no unique primary key. Instead its primary key is a composition of five foreign keys.
* Table TABLE_B and TABLE_A have a many-to-many relationship with each other.
When I create the entity manager for running the DDL scripts into the DB i´m getting "ORA-02270: no matching unique or primary key for this column-list".
These are my entities (sorry the portuguese terms, but i think the issue can be understood without translation...).
@Entity
@Table( name = "DESTAQUE_PDE" )
public class DestaquePDE implements Serializable {
private static final long serialVersionUID = 4694859522628884981L;
@Id
@GeneratedValue( strategy = GenerationType.SEQUENCE )
@Column( name = "ID_DESTAQUE_PDE", nullable = false )
private long id;
//Some fields were ommited here for simplicity....
@ManyToMany( cascade = CascadeType.ALL )
@JoinTable( name = "JOIN_DESTAQUES_CORRELACAO",
joinColumns = @JoinColumn( name = "JOIN_ID_DESTAQUE", referencedColumnName = "ID_DESTAQUE_PDE" ),
inverseJoinColumns = {@JoinColumn( name = "JOIN_ID_COR_PUB_ALVO", referencedColumnName = "FK_ID_PUBLICO_ALVO" ),
@JoinColumn( name = "JOIN_ID_COR_RES_LINHA", referencedColumnName = "FK_ID_RESOLUCAO_LINHA" ),
@JoinColumn( name = "JOIN_ID_MOD_CRED", referencedColumnName = "FK_ID_MODALIDADE_CREDITO" ),
@JoinColumn( name = "JOIN_ID_AG_FIN", referencedColumnName = "FK_ID_AGENTE_FINANCEIRO" ),
@JoinColumn( name = "JOIN_ID_PROG_LINHA", referencedColumnName = "FK_ID_PROGRAMA_LINHA" )}
private List<EntradaTabelaCorrelacao> correlacoes;
@Entity
@Table( name = "CORRELACAO" )
@IdClass( TabelaCorrelacaoPK.class )
public class EntradaTabelaCorrelacao implements Serializable {
private static final long serialVersionUID = -3337072470212918325L;
@Id
@Column( name = "FK_ID_PUBLICO_ALVO" )
private long idPublicoAlvo;
@Id
@Column( name = "FK_ID_RESOLUCAO_LINHA" )
private long idResolucaoLinha;
@Id
@Column( name = "FK_ID_MODALIDADE_CREDITO" )
private long idModalidadeCredito;
@Id
@Column( name = "FK_ID_AGENTE_FINANCEIRO" )
private long idAgenteFinanceiro;
@Id
@Column( name = "FK_ID_PROGRAMA_LINHA" )
private long idProgramaLinha;
@Column( name = "CS_SITUACAO", nullable = false, length = 1 )
private String situacao;
@ManyToMany( mappedBy = "correlacoes" )
private List<DestaquePDE> destaquesPDE;
//more relationships ommited for simplicity....
public class TabelaCorrelacaoPK implements Serializable {
private long idPublicoAlvo;
private long idResolucaoLinha;
private long idModalidadeCredito;
private long idAgenteFinanceiro;
private long idProgramaLinha;
//getters and setters ommited....
These are part of the DDLs generated by toplink:
CREATE TABLE DESTAQUE_PDE (
ID_DESTAQUE_PDE NUMBER(19) NOT NULL,
VL_ALOCACAO_AUTORIZADA NUMBER(16,2) NOT NULL,
VL_TOTAL NUMBER(16,2) NOT NULL,
QT_OPERACOES NUMBER(16,2) NOT NULL,
NM_DESTAQUE_PDE VARCHAR2(255) NOT NULL,
VL_ESTIMATIVA_REAPLICACAO NUMBER(16,2) NOT NULL,
VL_MONTANTE NUMBER(16,2) NOT NULL,
FK_ID_PDE NUMBER(19) NOT NULL,
FK_RESOLUCAO_PROGRAMA NUMBER(19) NOT NULL,
PRIMARY KEY (ID_DESTAQUE_PDE)
CREATE TABLE CORRELACAO (
FK_ID_PUBLICO_ALVO NUMBER(19) NOT NULL,
FK_ID_RESOLUCAO_LINHA NUMBER(19) NOT NULL,
FK_ID_MODALIDADE_CREDITO NUMBER(19) NOT NULL,
FK_ID_AGENTE_FINANCEIRO NUMBER(19) NOT NULL,
FK_ID_PROGRAMA_LINHA NUMBER(19) NOT NULL,
CS_SITUACAO VARCHAR2(1) NOT NULL,
PRIMARY KEY (FK_ID_PUBLICO_ALVO, FK_ID_RESOLUCAO_LINHA, FK_ID_MODALIDADE_CREDITO, FK_ID_AGENTE_FINANCEIRO, FK_ID_PROGRAMA_LINHA)
ALTER TABLE DESTAQUE_PDE
ADD CONSTRAINT FK_DESTAQUE_PDE_FK_ID_PDE
FOREIGN KEY (FK_ID_PDE)
REFERENCES PDE (ID_PDE)
ALTER TABLE DESTAQUE_PDE
ADD CONSTRAINT DESTAQUEPDEFKRESOLUCAOPROGRAMA
FOREIGN KEY (FK_RESOLUCAO_PROGRAMA)
REFERENCES RESOLUCAO_PROGRAMA (ID_RESOLUCAO_PROGRAMA)
(*) ALTER TABLE CORRELACAO
ADD CONSTRAINT CORRELACAO_FK_ID_PUBLICO_ALVO
FOREIGN KEY (FK_ID_PUBLICO_ALVO)
REFERENCES PUBLICO_ALVO (ID_PUBLICO_ALVO)
ALTER TABLE CORRELACAO
ADD CONSTRAINT CORRELACAOFKID_RESOLUCAO_LINHA
FOREIGN KEY (FK_ID_RESOLUCAO_LINHA)
REFERENCES RESOLUCAO_LINHA (ID_RESOLUCAO_LINHA)
ALTER TABLE CORRELACAO
ADD CONSTRAINT CRRELACAOFKIDMODALIDADECREDITO
FOREIGN KEY (FK_ID_MODALIDADE_CREDITO)
REFERENCES MODALIDADE_CREDITO (ID_MODALIDADE_CREDITO)
ALTER TABLE CORRELACAO
ADD CONSTRAINT CORRELACAOFKIDAGENTEFINANCEIRO
FOREIGN KEY (FK_ID_AGENTE_FINANCEIRO)
REFERENCES AGENTE_FINANCEIRO (ID_AGENTE_FINANCEIRO)
ALTER TABLE CORRELACAO
ADD CONSTRAINT CORRELACAOFK_ID_PROGRAMA_LINHA
FOREIGN KEY (FK_ID_PROGRAMA_LINHA)
REFERENCES PROGRAMA_LINHA (ID_PROGRAMA_LINHA)
As I told before, the error i´m getting with these mappings is:
ORA-02270: no matching unique or primary key for this column-list
The error occurs exactly when executing the instruction with (*).
Thanks in advance for any help!
Regards
LorenoThe error says that the table PUBLICO_ALVO does not have a primary key or unique constraint for (ID_PUBLICO_ALVO), so you cannot define a foreign key constraint to it. This table was not included in your DDL, how was it created? You need to add a primary key or unique constraint in this table on this field.
If you do not wish to have the unique or foreign key defined you can just ignore the error, it is just a warning.
<p>---
<br>James Sutherland
<br>Oracle TopLink, EclipseLink
<br>Wiki: Java Persistence, EclipseLink -
Hi,
I am trying to create a composite foriegn key. I have created my primary key as a composite key, made up of three fields.
Table 1
PatientID - Made from 3 fields(a,b,c)(primry key)
Table B
PatiendID- (should be the foreign key which references table1)
However i am finding that when i try to create my constraint i get the following messages
error 02270 - no matching unique or primarty key for this column list.
below is the sample code i am using to create my foreign key)
(ALTER TABLE XD_PatientSedation ADD CONSTRAINT fk_Sedation_PatientID FOREIGN KEY (PatientID)REFERENCES XD_Patient_Demographics(PatientID)
I am really stuck on this and dont quite know what to do.
Hope you can help.
Thanks
JagdishJust speaking about design, when you want to use a foreign key, it already means that the referenced columns represent something important enough to be a primary key of some other table. I don't understand the business logic of your example (using real table and column names would help), but the solution is probably one of these two :
a) your foreign key should in fact refer to (a,b,c), the complete primary key of the first table (what was suggested by the others).
b) your foreign key should stay as 'a' (patientid?), you should have a third table (patients?) whose primary key is 'a', and your "Table 1" should have a foreign key on 'a', referencing the third table. In this case you may find it silly to create a new table with only one column, but I would bet that you will very soon think of interesting attributes which could be added to this table.
In any case, I think that Oracle did a good job by forcing an improvement of your design ! -
How to use Concatenation option in Foreign Key
Hi,
I have 2 tables.
Master Table : Father(a varchar2(10),b varchar2(10)
Child Table : Child (c varcahr2(20))
In the child Table i have stored the following Father.A||Father.B
Child.C = Father.a + Father.B
I want to create a Foreign Key Relation for this.
I cant use '||' option.
Can any one please guide me.
ALTER TABLE child ADD CONSTRAINT fk_child FOREIGN KEY (c) REFERENCES father(a||b)
ON DELETE CASCADE;
This statement throws error.
Pls help me in thisWhy not create a third column on the Master table ?
alter table Father add c varchar2(20);
-- then perform an update
update Father set c := a|| b
commit
/and then create the constraint as;
ALTER TABLE child ADD CONSTRAINT fk_child FOREIGN KEY (c) REFERENCES father (c) ON DELETE CASCADE; -
Primary key foreign key dependencies
hi gems...
I have a table with composite primary key (COL1, COL2)..
create table TABLE1 (COL1, COL2);
alter table TABLE1 add constraint PK_TABLE1 primary key (COL1, COL2);
Now i am trying to make another table which will refer to the COL1 of the first table.
create table TABLE2 (COL3, COL4);
alter table TABLE2 add constarint FK_TABLE2 (COL3) references TABLE1(COL1);
but it is failing with "no matching unique or primary key" error.You have created a composite primary key, so there must be composite foreign key that references the composite primary key. You cannot create Foreign key that references to single column of the composite primary key.
-
Does a foreign key have to be a primary key
Hey all.I was checking on the database code written by sambapos.To my surprise, I found a foreign key that is not a primary key anywhere.
Is that possible?
If, so why?
I am really astonished.Limitations and Restrictions
A foreign key constraint does not have to be linked only to a primary key constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column; otherwise, a foreign key violation error message is returned. To make sure that all values of a composite foreign key constraint
are verified, specify NOT NULL on all the participating columns.
FOREIGN KEY constraints can reference only tables within the same database on the same server. Cross-database referential integrity must be implemented through triggers. For more information, see
CREATE TRIGGER (Transact-SQL).
FOREIGN KEY constraints can reference another column in the same table. This is referred to as a self-reference.
A FOREIGN KEY constraint specified at the column level can list only one reference column. This column must have the same data type as the column on which the constraint is defined.
A FOREIGN KEY constraint specified at the table level must have the same number of reference columns as the number of columns in the constraint column list. The data type of each reference column must also be the same as the corresponding column in the column
list.
The Database Engine does not have a predefined limit on either the number of FOREIGN KEY constraints a table can contain that reference other tables, or the number of FOREIGN KEY constraints that are owned by other tables that reference a specific table.
Nevertheless, the actual number of FOREIGN KEY constraints that can be used is limited by the hardware configuration and by the design of the database and application. We recommend that a table contain no more than 253 FOREIGN KEY constraints, and that it
be referenced by no more than 253 FOREIGN KEY constraints.
FOREIGN KEY constraints are not enforced on temporary tables.
If a foreign key is defined on a CLR user-defined type column, the implementation of the type must support binary ordering. For more information, see
CLR User-Defined Types.
A column of type varchar(max) can participate in a FOREIGN KEY constraint only if the primary key it references is also defined as type
varchar(max).
Read this article
http://msdn.microsoft.com/en-us/library/ms189049.aspx
Regards, Ashwin Menon My Blog - http:\\sqllearnings.com -
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 -- -
Using FOreign key constraints on tables in database.
I am student and novice in the field of ORACLE and PL/SQL and Database Creation. I had created a database consisting tables and got problem while applying foreign key constraints.
CUST_MSTR
CREATE TABLE "DBA_BANKSYS"."CUST_MSTR"("CUST_NO" VARCHAR2(10),
"FNAME" VARCHAR2(25), "MNAME" VARCHAR2(25), "LNAME" VARCHAR2(25),
"DOB_INC" DATE NOT NULL, "OCCUP" VARCHAR2(25), "PHOTOGRAPH" VARCHAR2(25),
"SIGNATURE" VARCHAR2(25), "PANCOPY" VARCHAR2(1), "FORM60" VARCHAR2(1));
(CUST_NO is PRIMARY KEY, )
-- EMP_MSTR
CREATE TABLE "DBA_BANKSYS"."EMP_MSTR"("EMP_NO" VARCHAR2(10),
"BRANCH_NO" VARCHAR2(10), "FNAME" VARCHAR2(25), "MNAME" VARCHAR2(25),
"LNAME" VARCHAR2(25), "DEPT" VARCHAR2(30), "DESIG" VARCHAR2(30));
(EMP_NO is primary key )
--NOMINEE_MSTR
CREATE TABLE "DBA_BANKSYS"."NOMINEE_MSTR"("NOMINEE_NO" VARCHAR2(10),
"ACCT_FD_NO" VARCHAR2(10), "NAME" VARCHAR2(75), "DOB" DATE,
RELATIONSHIP" VARCHAR2(25));
(NOMINEE_NO is primary key )
--ADDR_DTLS
CREATE TABLE "DBA_BANKSYS"."ADDR_DTLS"("ADDR_NO" NUMBER(6),
"CODE_NO" VARCHAR2(10), "ADDR_TYPE" VARCHAR2(1), "ADDR1" VARCHAR2(50),
"ADDR2" VARCHAR2(50), "CITY" VARCHAR2(25), "STATE" VARCHAR2(25),
"PINCODE" VARCHAR2(6));
( ADDR_NO is primary key )
Problem: I want to apply foreign key constraints on ADDR_DTLS table so that Before inserting value in ADDR_DTLS table it must check, VALUE in ADDR_DTLS.CODE_NO must be PRESENT either in attribute value CUST_MSTR.CODE_NO or EMP_MSTR.CODE_NO or NOMINEE_MSTR.CODE_NO table .
I applied the foreign key constraints using this syntax
CREATE TABLE "DBA_BANKSYS"."ADDR_DTLS"("ADDR_NO" NUMBER(6),
"CODE_NO" VARCHAR2(10), "ADDR_TYPE" VARCHAR2(1), "ADDR1" VARCHAR2(50),
"ADDR2" VARCHAR2(50), "CITY" VARCHAR2(25), "STATE" VARCHAR2(25),
"PINCODE" VARCHAR2(6),
constraints fk_add foreign key CODE_NO references CUST_MSTR. CODE_NO,
constraints fk_add1 foreign key CODE_NO references EMP_MSTR. CODE_NO,
constraints fk_add2 foreign key CODE_NO references NOMINEE_MSTR.CODE_NO);
(foreign key)
ADDR_DTLS.CODE_NO ->CUST_MSTR.CUST_NO
ADDR_DTLS.CODE_NO ->NOMINEE_MSTR.NOMINEE_NO
ADDR_DTLS.CODE_NO ->BRANCH_MSTR.BRANCH_NO
ADDR_DTLS.CODE_NO ->EMP_MSTR.EMP_NO
When I applied foreign key constraints this way, its gives a error called foreign key constraints violation. (I understand that, its searches the attribute value of ADDR_DTLS.CODE_NO in all the three tables must be present then the value will be inserted. But I want, if the value is in any of the three table then its should insert the value or its gives an error.)
Please help me out, though i put the question and i want too know how to apply the forign key in this way. and is there any other option if foreign key implementation is not pssible.If you are on 11g you can use ON DELETE SET NULL:
CREATE TABLE addr_dtls
( addr_no NUMBER(6) CONSTRAINT addr_pk PRIMARY KEY
, addr_cust_no CONSTRAINT addr_cust_fk REFERENCES cust_mstr ON DELETE SET NULL
, addr_emp_no CONSTRAINT addr_emp_fk REFERENCES emp_mstr ON DELETE SET NULL
, addr_nominee_no CONSTRAINT addr_nominee_fk REFERENCES nominee_mstr ON DELETE SET NULL
, addr_type VARCHAR2(1)
, addr1 VARCHAR2(50)
, addr2 VARCHAR2(50)
, city VARCHAR2(25)
, state VARCHAR2(25)
, pincode VARCHAR2(6) );In earlier versions you'll need to code some application logic to do something similar when a parent row is deleted, as otherwise the only options are to delete the dependent rows or raise an error.
btw table names can be up to 30 characters and don't need to end with MSTR or DTLS, so for example CUSTOMERS and ADDRESSES might be more readable than CUST_MSTR and ADDR_DTLS. Also if the Customer/Employee/Nominee PKs are generated from a sequence they should be numeric.
Edited by: William Robertson on Aug 15, 2010 6:47 PM -
Renaming Foreign Keys in the Relational Model
Hi,
I'm new to Data Modeler, we are using v 3.0.0.66.5 and Oracle 11g, and I'm trying to build a Logical and Relational model for a new application.
We always name our Primary Keys as ID, this is causing me a problem with my Foreign Keys names in the Relational Model, as they are showing as ID#. Is there a way to add the abbr. of the table to the Foreign Key?
Thanks in Advance
SueI always do that job using Naming Standard Templates. This sequence renames ALL FK COLUMNS for ALL TABLES only in RELATIONAL MODEL:
-Preferences > Data Modeler > Naming Standards > templates
-into the box "Column Foreign Key"
-Put something like that: {ref table}_{ref column}
-Then, go into your modeler tree, select the relational model, right click and use "Apply Naming Standards to Keys and Constraints"
-deselect all
-select the last option "Column Foreign Key"
-Go.
What if the names still collide? What if you want to do the job for some--but-not-ALL tables? forget the method above. A transformation script will do that.
You'll need some of these building blocks:
- table.getFKAssociations()
- keys.getRemoteTable().getAbbreviation()
- column.setName()
I'm novice to script coding, sorry I can't assemble a scripted solution right now.
Edited by: T. on May 31, 2011 8:50 AM -
Foreign Key Relationship.
Hi,
I asked a question in the link below(which I solved).
https://social.msdn.microsoft.com/Forums/en-US/514a4f48-b1fa-4fe7-bc2b-4c252b34cf50/insertion-of-null-value?forum=vbgeneral
Here my question is that:
We make relation of foreign keys to enforce user for accurate data insertion, but sometime we do need null values to be passed to attribute that is used as
Foreign key. We studied and know that Foreign keys are meant to except null values, which it doesn't(In simple way. I mean when we select an attribute as foreign key and check it to except nulls, then it should.)
As I explained in the upper link how I solved the problem, if similar problems have to be solved like that then,
Why we define Foreign Key over there, i mean it could be done without defining the Foreign key?
If it is necessary in any meaning then why we Enforce Foreign
Key Constraint as No,
to except nulls from user?
What effects does Enforce Foreign Key Constraint as No
gives to Foreign Key Constraints?
Thnx in advance.
Habib Ur RehmanHello Habib,
I do not think what you are seeing is normal and without having the exact DDL it will be hard to comment.
I suspect, you may had "NOT NULL" constraint on the foreign key column. thats why it is not allowing NULLs.
By definition, Foreign Key maintains(enforces) referential integrity and does allows NULLs. So, you should be able to enter nulls without having to disable the foreign key enforcement.
by setting
Enforce Foreign Key Constraint to NO, you are effectively disabling the enforcement. you are invalidating the whole purpose of the constraint.
The purpose of having that option(disabling foreign key) is to fasten the data load process bypassing the check(extra work) to make sure the value exists in the primary key table when importing large amounts of data. But to maintain the referential
integrity you should have that enabled.
I am not sure without having the ddl, where you did wrong.PLEASE POST YOUR DDL and it should be clear where it went wrong for you. but i hope this script below should help you understand...
CREATE TABLE [dbo].[Make]([sid] [int] NULL unique,[sname] [varchar](50) NULL)
go
CREATE TABLE [dbo].[Make_FK]([sno] [int] NULL unique,[sname] [varchar](50) NULL,[sid] [int] NULL
CONSTRAINT FK_MAKE FOREIGN KEY (sid) REFERENCES dbo.make (SID))
insert into make(sid,sname)
values(1,'sam')
insert into dbo.Make_FK(sno,sname,sid)
values(100,'somename',null)
select * from Make
--sid is null. SID is the foreig n key referring to sid in MAKE table.
select * from Make_FK
Hope it Helps!! -
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 errorThe 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.
Maybe you are looking for
-
Is it possible to generate a PDF and send it as a mail attachment ?
Hello All, While there are many contributions and suggestions on how to send a pdf form via email, I will like to find out if its possible to send a pdf as part of an email attachment WITHOUT even viewing it first ? Below is a brief descrption of w
-
IE HTTP close (reset) - port reuse causing firewall issues
Having an issue with some systems reusing the same TCP port number between sessions, causing the firewall to drop the connection. Internet Explorer is creating the HTTP socket connection to port 80. An ephemeral port (assigned by Windows) is bound to
-
How to draw a graph of tree structure (using shapes and lines)?
Hello, I tried to search this solution in the forum, and I see people asking and replying with solutions to similar situation, but I don't get what I am looking for. Also because I have never tried with graphs before. So, my problem is, I need a func
-
Hi! I had purchased Adobe Photoshop Lightroom 5 Full - English - Multiple Platforms - Download. Had received a serial number to activate my license. I am nott able to update this to the latest version. Tried entering the license key which I had recei
-
Fix for Perian 1.1 in QuickTime 7.5
As many people are aware, QuickTime 7.5 breaks some 3rd-party components. For me this was Perian 1.1, which I use solely for its subtitle capabilities. I installed the 7.5 update and lo and behold, the subtitles for a movie I downloaded weren't showi