Syntax error in Oracle create table query - sql

CREATE TABLE Emp OF Emp_t(eno PRIMARY KEY, edept REFERENCES Dept);
There near the PRIMARY KEY, it will display a syntax error as expected not null. I need to solve it.
Below is the rest of queries in that schema.
CREATE TYPE Emp_t AS OBJECT(eno number(4),ename varchar2(15),edept ref dept_t,salary number(8,2));
/
CREATE TYPE Dept_t AS OBJECT(dno number(2),dname varchar2(12),mgr ref emp_t);
/
CREATE TYPE Proj_t AS OBJECT(pno number(4),pname varchar2(15),pdept ref dept_t,budget number(10,2));
/
CREATE TABLE Dept OF Dept_t(dno PRIMARY KEY, mgr REFERENCES Emp);
CREATE TABLE Proj OF Proj_t(pno PRIMARY KEY, pdept REFERENCES dept);
Error is dispalyed as in the following image.

As #LostInAlabama suggested, you can create the tables and add the circular constraints afterwards:
CREATE TABLE Dept OF Dept_t(dno PRIMARY KEY);
CREATE TABLE Proj OF Proj_t(pno PRIMARY KEY);
CREATE TABLE Emp OF Emp_t(eno PRIMARY KEY);
ALTER TABLE Dept MODIFY (mgr REFERENCES Emp);
or preferably with named constraints:
ALTER TABLE Dept ADD (CONSTRAINT Dept_FK_Emp FOREIGN KEY (mgr) REFERENCES Emp);
ALTER TABLE Emp ADD (CONSTRAINT Emp_FK_Dept FOREIGN KEY (edept) REFERENCES Dept);
ALTER TABLE Proj ADD (CONSTRAINT Proj_FK_Dept FOREIGN KEY (pdept) REFERENCES Dept);

Related

Add multiple foreign keys to existing table in Oracle

I want to add multiple foreign keys to existing table in Oracle database. Following sql query gives me an error. One by one I can add foreign key constraint. But I want to do this within one statement like below.
ALTER TABLE address
ADD CONSTRAINT fk_customer_id FOREIGN KEY (customer_id)
REFERENCES customer (id) ON DELETE CASCADE ,
ADD CONSTRAINT fk_city_id FOREIGN KEY (city_id)
REFERENCES city (id) ON DELETE CASCADE;
Any idea how to do this?
That's not entirely true (what #Thorsten has said). You can add two constraints at a time.
SQL> create table test (empno number, deptno number);
Table created.
SQL>
SQL> alter table test add
2 ( constraint fk_test_emp foreign key (empno) references emp (empno),
3 constraint fk_test_dept foreign key (deptno) references dept (deptno)
4 );
Table altered.
SQL>

Create table with foreign key to an other table created below in sql file

My problem is that i have two tables with each table having a foreign key to the other table.
Each time , i execute the SQL file containing the creation of the two tables, it gives me an error that he doesn't find the other table. I'm working with sqlplus to execute the sql file.
Here's an example of SQL file i tried with :
create table A(
Age number(3),
name number(3) constraint A_FK references B(name))
/
create table B(
Age number(3) constraint B_FK references A(Age),
name number(3))
And even if i reverse the order, it gives the same error.
Thanks for help.
This is a problem of cycles in foreign keys. One method is to add all foreign keys after table creation (as I think the other answers propose).
You can also just do that for the first table:
create table A (
Age number(3) primary key,
name number(3)
);
create table B (
name number(3) primary key,
Age number(3),
constraint B_FK foreign key (age) references A(Age)
);
alter table B add constraint A_FK foreign key (name) references B(name);
Here is a db<>fiddle.
Notes:
Foreign keys should reference primary keys, so I added that declaration as well.
I recommend making the primary key the first column in the table.
You can also define the constraint inline for one of the tables (i.e. age number(3) constraint b_fk references a(age)).
The table column(s) that is referred by a foreign key must exist at the time when the constraint is created. Since you have some kind of cyclic reference between the tables, you need to do this in three steps:
first create one table without the foreign key
create the second table (with its foreign key)
finally add the foreign key to the first table with an alter table statement
You also need the referred column to have a unique or primary key constraint set up, otherwise you would get error ORA-02270: no matching unique or primary key for this column-list.
create table A(
age number(3) primary key,
name number(3)
);
create table B(
age number(3) constraint B_FK references A(Age),
name number(3) primary key
);
alter table A add constraint A_FK foreign key (name) references B(name);
Demo on DB Fiddle
Side note: I am quite suspicious about your sample structure, but this could be because your oversimplified it in the question.
It fails because the reference table doesn't exist yet.
Create the tables without the key first. Then drop one and recreated it with the reference. Then drop the 2nd and recreate it with the reference.
Create table first and then ADD the CONSTRAINT
ALTER TABLE A
ADD FOREIGN KEY (name) REFERENCES B(name);
ALTER TABLE B
ADD FOREIGN KEY (age) REFERENCES A(age);

SQL "Alter Table" for foreign key

So I'm learning some SQL as a bit of a side project since my SQL sucks. I have the following table I created:
CREATE TABLE deliveries (
pid INTEGER,
FOREIGN KEY (pid) REFERENCES person_lives_at,
);
I want to alter it to be a table like this one:
CREATE TABLE deliveries (
pid INTEGER,
FOREIGN KEY (pid) REFERENCES employee,
);
How can I achieve that? I'm using Oracle SQL Developer
Since you created an FK constraint without a name, oracle assigned a system-generated name to the constraint like SYS_xxxxxx. To find the constraint name:
select constraint_name from all_Constraints
where table_name = 'DELIVERIES'
In my test case, it returned "SYS_C0016779". I then drop the constraint:
alter table deliveries drop constraint SYS_C0016779
Then add the new constraint:
ALTER TABLE deliveries
ADD CONSTRAINT PID_EMP_FK -- or whatever you want to call it.
FOREIGN KEY (pid)
REFERENCES employee(pid); -- or whatever the name of the column is

can't delete foreign and primary key

can't delete the primary and foreign key, it's simple table but i don't why this error
create table student (
s_ID int ,
S_NAMe varchar2 (10),
S_major varchar2(20),
D_ID number (10) ,
Constraint PK_s_ID primary key (s_ID),
constraint FK_D_ID foreign key (D_ID) references dep (D_ID) );
ALTER TABLE student DROP CONSTRAINT PK_s_ID cascade;
alter table student drop constraint FK_D_ID;
ERROR at line 1:
ORA-02443: Cannot drop constraint - nonexistent constraint
You SQL commands looks correct. You can use following command to make sure constraint exists.
SELECT * FROM user_cons_columns WHERE table_name = 'STUDENT'
If it returns no result, that means you either did not create a constraint or already dropped. You may be trying to re-run the same alter command more than once.

How to add a foreign key referring to itself in SQL Server 2008?

I have not seen any clear, concise examples of this anywhere online.
With an existing table, how do I add a foreign key which references this table? For example:
CREATE TABLE dbo.Projects(
ProjectsID INT IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
);
How would I write a command to add a foreign key which references the same table? Can I do this in a single SQL command?
I'll show you several equivalent ways of declaring such a foreign key constraint. (This answer is intentionally repetitive to help you recognise the simple patterns for declaring constraints.)
Example: This is what we would like to end up with:
Case 1: The column holding the foreign keys already exists, but the foreign key relationship has not been declared / is not enforced yet:
In that case, run this statement:
ALTER TABLE Employee
ADD FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
Case 2: The table exists, but it does not yet have the foreign key column:
ALTER TABLE Employee
ADD ManagerId INT, -- add the column; everything else is the same as with case 1
FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
or more succinctly:
ALTER TABLE Employee
ADD ManagerId INT REFERENCES Employee (Id);
Case 3: The table does not exist yet.
CREATE TABLE Employee -- create the table; everything else is the same as with case 1
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT
);
ALTER TABLE Employee
ADD FOREIGN KEY (ManagerId) REFERENCES Employee (Id);
or, declare the constraint inline, as part of the table creation:
CREATE TABLE Employee
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT,
FOREIGN KEY (ManagerId) REFERENCES Employee (Id)
);
or even more succinctly:
CREATE TABLE Employee
(
Id INT NOT NULL PRIMARY KEY,
ManagerId INT REFERENCES Employee (Id)
);
P.S. regarding constraint naming: Up until the previous revision of this answer, the more verbose SQL examples contained CONSTRAINT <ConstraintName> clauses for giving unique names to the foreign key constraints. After a comment by #ypercube I've decided to drop these clauses from the examples, for two reasons: Naming a constraint is an orthogonal issue to (i.e. independent from) putting the constraint in place. And having the naming out of the way allows us to focus on the the actual adding of the constraints.
In short, in order to name a constraint, precede any mention of e.g. PRIMARY KEY, REFERENCES, or FOREIGN KEY with CONSTRAINT <ConstraintName>. The way I name foreign key constraints is <TableName>_FK_<ColumnName>. I name primary key constraints in the same way, only with PK instead of FK. (Natural and other alternate keys would get the name prefix AK.)
You can add the column and constraint in one operation
ALTER TABLE dbo.Projects ADD
parentId INT NULL,
CONSTRAINT FK FOREIGN KEY(parentid) REFERENCES dbo.Projects
Optionally you could specify the PK column in brackets after the referenced table name but it is not needed here.
If the table already exists: Assuming you don't already have a column to store this data. If you do then skip this step.
ALTER TABLE [dbo].[project]
ADD [fkProjectsId] INT;
GO
ALTER TABLE [dbo].[projects]
ADD CONSTRAINT [FK_Projects_ProjectsId] FOREIGN KEY ([fkProjectsId]) REFERENCES [dbo].[Projects] ([ProjectsID])
GO