I'm new to sqlplus and was trying to run a sql script that creates a few tables, but once I try to run it, it gives me an error saying that the table or view doesnt exist and I dont know how to fix this error.
My script is:
drop table Borrower;
create table Borrower (
bid char(100) not null,
password char(100) not null,
name char(100) null,
address char(100) null,
phone char(100) null,
emailAddress char(100) null,
sinOrStNo char(100) null,
expiryDate date null,
--type ENUM('student','faculty','staff'),
type char(100) not null,
--CONSTRAINT Btype_check CHECK (type IN ('student','faculty','staff')),
FOREIGN KEY (type) references BorrowerType(type),
PRIMARY KEY (bid));
grant select on Borrower to public;
"unique/primary keys in table referenced by foreign keys "
Data integrity is crucial to a properly run database so Oracle will not let us drop a table if its primary key is referenced by another table's foreign key. So it hurls ORA-02449.
So, given this set up:
create table t_parent (
id number not null
, constraint tp_pk primary key (id)
);
create table t_child (
id number not null
, p_id number not null
, constraint tc_pk primary key (id)
, constraint tc_tp_fk foreign key (p_id)
references t_parent (id)
);
There are three ways to drop table t_parent.
run drop table t_child first: no child table, no foreign key.
Remove the blocking foreign key: alter table t_child drop constraint tc_pc_fk.
A variant on the previous one, let the database figure out the foreign keys:
drop table t_parent cascade constraints.
The first option is the most proper, because it leaves the database in a valid state (no tables, no possibility of data integrity corruption). The valid use for the third approach is a script which razes all the tables from a schema: it's easy to generate such a script from the data dictionary.
The order that you drop or create tables are important because if you have foreign keys referencing another table, you cant delete that table before deleting your own table.
In this example, the Borrower table has to be dropped before the BorrowerType table.
Related
I'm creating a database for my assignment. I had to create 2 tables namely Customer and Job through the "New Query" option in SQL server. After creating both of them, I wanted to add Job_ID (A primary key) from Job table as a foreign key to the Customer table. As I have already created the Customer table, The only option I had was to ALTER the customer table. But after altering, I seemed to get this unusual error.
Msg 1769, Level 16, State 1, Line 1
Foreign key 'Job_ID' references invalid column 'Job_ID' in referencing table 'CUSTOMER'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.
I can provide you with any more info if necessary.
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
CREATE TABLE JOB
(Job_ID INT NOT NULL PRIMARY KEY,
Pickup_location VARCHAR (10) NOT NULL,
Destination VARCHAR (10) NOT NULL,
Customer_ID INT FOREIGN KEY REFERENCES CUSTOMER(Customer_ID));
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
This looks like the same issue as described here.
When you try to create your foreign key:
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
You are saying that you want to use the field Job_ID from the table CUSTOMER:
ALTER TABLE CUSTOMER ADD FOREIGN KEY (Job_ID)
and that the values in this field should match values in the Job_ID column from the table JOB:
REFERENCES JOB(Job_ID);
The problem is that your CUSTOMER table doesn't have a Job_ID column, based on its definition:
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
The fields in the CUSTOMER table are Customer_ID,Customer_Name,Gender,Customer_Type,Addresss and Telephone_No.
So you either need to add a Job_ID column to the CUSTOMER table, or specify a different field to use in your ALTER TABLE statement - one which does exist in the CUSTOMER table.
More information on ALTER TABLE and ADD FOREIGN KEY specifically can be found here.
I'm having trouble understanding how to setup my foreign key reference. I'm trying to make a reference between tables Lägenheter and Arbetslista so that one row in Lägenheter belong to many rows in Arbetslista.
I have created tables likes this:
CREATE TABLE Deltagare (
Deltagarnr int PRIMARY KEY,
Namn varchar(30),
Typ varchar(30)
);
CREATE TABLE Uppgifter (
Uppgift varchar(30) PRIMARY KEY,
Typ varchar(30),
Pris money
);
CREATE TABLE Arbetslista (
Deltagarnr int not null,
Datum date not null,
Uppgift varchar(30) not null,
Lägenhetsnr int not null,
PRIMARY KEY (Deltagarnr, Datum, Uppgift),
FOREIGN KEY (Deltagarnr) REFERENCES Deltagare(Deltagarnr),
FOREIGN KEY (Uppgift) REFERENCES Uppgifter(Uppgift)
);
Then I import some data from a .mdb file to all three tables.
After that I add another table:
CREATE TABLE Lägenheter(
lägenhetsnummer int PRIMARY KEY,
gatuadress varchar(30),
kvadrater int
);
It all works fine until this last step:
ALTER TABLE Arbetslista
ADD FOREIGN KEY (Lägenhetsnr) REFERENCES Lägenheter(lägenhetsnummer)
;
Here I get this error message:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__403A8C7D". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.
After that I have also tried to delete all data from Arbetslista and then execute the mentioned ALTER TABLE again. It works, but then I get an error trying to import the data again:
Hresult: 0x80004005 Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Arbetslis__Lägen__412EB0B6". The conflict occurred in database "Hushåll", table "dbo.Lägenheter", column 'lägenhetsnummer'.".
(SQL Server Import and Export Wizard)
Why is this not possible when the other foreign keys seems to work fine?
There are rows in Arbetslista table, for which the value of Lägenhetsnr doesn't exists in field lägenhetsnummer of table Lägenheter. You must clean the existing data to be able to create the foreign key like that.
Check your data by executing this script:
select * from Arbetslista a where not exists (select * from Lägenheter l where l.lägenhetsnummer = a.Lägenhetsnr)
After importing the data into Arbetslista, the column Lägenhetsnr was initialize to some value ( say XYZ).
later, when trying to add the FOREIGN KEY to Arbetslista, SQL try to meet this, however it cannot find row with primary key lägenhetsnummer = XYZ and the statement would be terminated.
I think the best is to create the 4 table first then clean the data and try to import it.
I've created an ADO.NET model via the database first approach.
One of my tables which is listed when creating the model doesn't actually get added to it.
The table has a multi-column primary key, composed of two foreign keys.
CREATE TABLE ForumAccess
(
UserID INT FOREIGN KEY REFERENCES Users(UserID) NOT NULL,
ForumID INT FOREIGN KEY REFERENCES Forums(ForumID) NOT NULL,
CONSTRAINT ForumAccessID PRIMARY KEY (UserID, ForumID),
);
It does show up when I have to select which tables to add, but then it seems to be skipped. No class is generated for it, and it's not shown in the .edmx file.
Part of my application depends on the existence of this table. I have another table which has a multi-column primary key, and another DateTime type column. That table does get added.
That table is:
CREATE TABLE Moderators
(
UserID INT FOREIGN KEY REFERENCES Users(UserID) NOT NULL,
ForumID INT FOREIGN KEY REFERENCES Forums(ForumID) NOT NULL,
TimeOfAddition DateTime NOT NULL, -- When the mod was added as a mod.
CONSTRAINT ModeratorID PRIMARY KEY (UserID, ForumID),
);
Why does the Moderators table get added, but the ForumAccess table doesn't?
There is no error, or any warning that I can see.
What am I missing?
I have a language map table that each entry has the possibility of a foreign key relationship with a few different tables. What is the best schema to deal with this configuration?
Tables: LanguageMap, TableA, TableB
These are the two possibility:
1. Lookup Column Method - No Foreign Key Constraints:
Create Table LanguageMap (
Id int not null primary key,
Language nvarchar not null,
Value nvarchar not null,
Type nvarchar not null, -- 'TableA', 'TableB', etc.
ForeignTableId int not null -- Is Foreign key to another table dependent on the type of the row.
)
2. Multiple Foreign Key Columns
create Table LanguageMap(
Id int not null primary key,
Language nvarchar not null,
Value nvarchar not null,
Type nvarchar not null, -- 'Activity', 'Verb', etc.
TableAId int null,
TableBId int null
)
alter table LanguageMap add constraint FK_LanguageMap_TableA
foreign key (TableAId) references TableA (Id)
alter table LanguageMap add constraint FK_LanguageMap_TableA
foreign key (TableBId) references TableB (Id)
alter table LanguageMap add constraint CK_LanguageMap_OneIsNotNull
check (TableAId is not null or TableBId is not null)
go
alter table LanguageMap add constraint CK_LanguageMap_OneIsNull
check (TableAId is null or TableBId is null)
go
The foreign key constraints are based on Foreign Key for either-or column?
There is another alternative, called "Shared Primary Key". You can look this up. If TableA, TableB, TableC, etc. all "inherit" their PK as a copy of the PK from some Master table, called "TableMaster" for example, then you can just use that as an FK in LanguageMap.
The correct joins will select the correct instances.
The shared primary key is often used in conjunction with a design pattern called "Class Table Inheritance". Without knowing what TableA, TableB, TableC, etc. are about, I can't say whether Class Table Inheritance is relevant to your case.
In any event, look up both "Shared Primary Key" and "Class Table Inheritance" for further reading.
There are tags with those names in this area.
I have two tables, Table JOB and Table USER, here is the structure
CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID NUMBER,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
);
CREATE TABLE USER
(
ID NUMBER NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
);
Now, i want to add foreign key constraint to JOB referencing to USER table, as
Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USER(ID);
this throws Oracle (ORA-02270) : no matching unique or primary key for this column-list error, doing some investigation it appears that we need to have either unique key or primary key constraint on USERID but I cannot have that as one USERID can have multiple JOBS associated with him, any thoughts or suggestions on how to fix this issue?
Researched ORA-02270 and SO related question
The ORA-2270 error is a straightforward logical error: it happens when the columns we list in the foreign key do not match a primary key or unique constraint on the parent table. Common reasons for this are
the parent lacks a PRIMARY KEY or UNIQUE constraint altogether
the foreign key clause references the wrong column in the parent table
the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
Neither appears to be the case in your posted code. But that's a red herring, because your code does not run as you have posted it. Judging from the previous edits I presume you are not posting your actual code but some simplified example. Unfortunately in the process of simplification you have eradicated whatever is causing the ORA-2270 error.
SQL> CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID NUMBER,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
); 2 3 4 5 6
Table created.
SQL> CREATE TABLE USER
(
ID NUMBER NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
); 2 3 4 5
CREATE TABLE USER
*
ERROR at line 1:
ORA-00903: invalid table name
SQL>
That statement failed because USER is a reserved keyword so we cannot name a table USER. Let's fix that:
SQL> 1
1* CREATE TABLE USER
SQL> a s
1* CREATE TABLE USERs
SQL> l
1 CREATE TABLE USERs
2 (
3 ID NUMBER NOT NULL ,
4 CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
5* )
SQL> r
1 CREATE TABLE USERs
2 (
3 ID NUMBER NOT NULL ,
4 CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
5* )
Table created.
SQL> Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USERS(ID);
Table altered.
SQL>
And lo! No ORA-2270 error.
Alas, there's not much we can do here to help you further. You have a bug in your code. You can post your code here and one of us can spot your mistake. Or you can check your own code and discover it for yourself.
Note: an earlier version of the code defined HOB.USERID as VARCHAR2(20). Because USER.ID is defined as a NUMBER the attempt to create a foreign key would have hurl a different error:
ORA-02267: column type incompatible with referenced column type
An easy way to avoid mismatches is to use foreign key syntax to default the datatype of the column:
CREATE TABLE USERs
(
ID number NOT NULL ,
CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
);
CREATE TABLE JOB
(
ID NUMBER NOT NULL ,
USERID constraint FK_USERID references users,
CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
);
The data type in the Job table (Varchar2(20)) does not match the data type in the USER table (NUMBER NOT NULL).
In my case the problem was cause by a disabled PK.
In order to enable it:
I look for the Constraint name with:
SELECT * FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'referenced_table_name';
Then I took the Constraint name in order to enable it with the following command:
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name;
We have the following script for create a new table:
CREATE TABLE new_table
(
id NUMBER(32) PRIMARY KEY,
referenced_table_id NUMBER(32) NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
FOREIGN KEY (referenced_table_id)
REFERENCES referenced_table (id)
);
and we were getting this error on execution:
[42000][2270] ORA-02270: no matching unique or primary key for this
column-list
The issue was due to disabled primary key of the referenced table in our case. We have to enable it using the following sql:
ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;
after that we created new table using first script without any issues
The scheme is correct, User.ID must be the primary key of User, Job.ID should be the primary key of Job and Job.UserID should be a foreign key to User.ID. Also, your commands appear to be syntactically correct.
So what could be wrong? I believe you have at least a Job.UserID which doesn't have a pair in User.ID. For instance, if all values of User.ID are: 1,2,3,4,6,7,8 and you have a value of Job.UserID of 5 (which is not among 1,2,3,4,6,7,8, which are the possible values of UserID), you will not be able to create your foreign key constraint. Solution:
delete from Job where UserID in (select distinct User.ID from User);
will delete all jobs with nonexistent users. You might want to migrate these to a copy of this table which will contain archive data.
Most Probably when you have a missing Primary key is not defined from parent table. then It occurs.
Like Add the primary key define in parent as below:
ALTER TABLE "FE_PRODUCT" ADD CONSTRAINT "FE_PRODUCT_PK" PRIMARY KEY ("ID") ENABLE;
Hope this will work.
I faced the same issue in my scenario as follow:
I created textbook table first with
create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );
Then chapter table:
create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40),
constraint pk_chapter primary key(txtbk_isbn,chapter_title),
constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));
Then topic table:
create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));
Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn) references textbook(txtbk_isbn),
foreign key (chapter_title) references chapter(chapter_title),
foreign key (topic_id) references topic (topic_id));
The solution was to refer to composite foreign key as below:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title),
foreign key (topic_id) references topic (topic_id));
Thanks to APC post in which he mentioned in his post a statement that:
Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED
When running this command:
ALTER TABLE MYTABLENAME MODIFY CONSTRAINT MYCONSTRAINTNAME_FK ENABLE;
I got this error:
ORA-02270: no matching unique or primary key for this column-list
02270. 00000 - "no matching unique or primary key for this column-list"
*Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement
gives a column-list for which there is no matching unique or primary
key constraint in the referenced table.
*Action: Find the correct column names using the ALL_CONS_COLUMNS
The referenced table has a primary key constraint with matching type. The root cause of this error, in my case, was that the primary key constraint was disabled.
Isn't the difference between your declaration of USERID the problem
JOB: UserID is Varchar
USER: UserID is Number?
If primary key is not already defined on parent table then this issue may arise. Please try to define the primary key on existing table.
For eg:
ALTER TABLE table_name
ADD PRIMARY KEY (the_column_which_is_primary_key);
create table articles(code varchar2(30)constraint articles_pk primary key,titre varchar2(30),
support varchar2(30) constraint support_fk references supports(support),type_support varchar2(30),
numeroDePage varchar2(30),datepublication date,categorie varchar2(30)constraint categorie_fk references organismes(categorie),
tendance varchar2(30)constraint tendance_fk references apreciations(tendance));