Foreign KEY Using SQL/ORACLE - database

I'm trying to declare a FOREIGN KEY using SQL but i'm always getting that error :
FOREIGN KEY (Dno) REFERENCES DEPARTMENT (Dnumber))
ERROR at line 14: ORA-00942: table or view does not exist
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn))
*
ERROR at line 8: ORA-00942: table or view does not exist
This is the code i'm using :
CREATE TABLE employee (fname VARCHAR (15) NOT NULL,
minit CHAR,
lname VARCHAR (15) NOT NULL,
ssn CHAR (9) NOT NULL,
bdate DATE,
address VARCHAR (30),
sex CHAR,
salary DECIMAL (10, 2),
super_ssn CHAR (9),
dno INT NOT NULL,
PRIMARY KEY (ssn),
FOREIGN KEY (super_ssn) REFERENCES employee (ssn),
FOREIGN KEY (dno) REFERENCES department (dnumber));
CREATE TABLE department (dname VARCHAR (15) NOT NULL,
dnumber INT NOT NULL,
mgr_ssn CHAR (9) NOT NULL,
mgr_start_date DATE,
PRIMARY KEY (dnumber),
UNIQUE (dname),
FOREIGN KEY (mgr_ssn) REFERENCES employee (ssn));

Since your employee table create statement has references to the department table, you'll need to make sure the department table is created first. However, you have a reference to the employee table as part of the create department table script. Circular references ahoy!
Fortunately, you can create constraints separately from the create table script, which is what you'll have to do in this case, e.g.:
CREATE TABLE employee (fname VARCHAR (15) NOT NULL,
minit CHAR,
lname VARCHAR (15) NOT NULL,
ssn CHAR (9) NOT NULL,
bdate DATE,
address VARCHAR (30),
sex CHAR,
salary DECIMAL (10, 2),
super_ssn CHAR (9),
dno INT NOT NULL,
PRIMARY KEY (ssn),
FOREIGN KEY (super_ssn) REFERENCES employee (ssn));
CREATE TABLE department (dname VARCHAR (15) NOT NULL,
dnumber INT NOT NULL,
mgr_ssn CHAR (9) NOT NULL,
mgr_start_date DATE,
PRIMARY KEY (dnumber),
UNIQUE (dname),
FOREIGN KEY (mgr_ssn) REFERENCES employee (ssn));
alter table employee add constraint emp_dept_fk FOREIGN KEY (dno) REFERENCES department (dnumber);

Related

Insert new record with composite primary key, which consists of two foreign keys from different tables

Please help me figure out how to Insert new record with composite primary key, which consists of two foreign keys from different tables.
I am working in C#, WPF if that matters.
I have three tables: Sales, SaleItem, Item.
CREATE TABLE [dbo].[Sales] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[saleTime] DATETIME NOT NULL,
[customerID] INT NULL,
[TIN] INT NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED ([saleID] ASC),
CONSTRAINT [FK_Sales_Customers] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customers] ([customerID]),
CONSTRAINT [FK_Sales_Company] FOREIGN KEY ([TIN]) REFERENCES [dbo].[Company] ([TIN])
);
CREATE TABLE [dbo].[Item] (
[ItemSKU] INT IDENTITY (1, 1) NOT NULL,
[itemName] NVARCHAR (50) NOT NULL,
[volume] FLOAT (53) NOT NULL,
[measureUnit] NVARCHAR (50) NOT NULL,
[producer] NVARCHAR (50) NOT NULL,
[supplierID] INT NOT NULL,
[retailPrice] NUMERIC (18) NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY CLUSTERED ([ItemSKU] ASC),
CONSTRAINT [FK_Item_Suppliers] FOREIGN KEY ([supplierID]) REFERENCES [dbo].[Suppliers] ([supplierID])
);
CREATE TABLE [dbo].[SaleItem] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[itemSKU] INT NOT NULL,
[quantity] INT NOT NULL,
CONSTRAINT [PK_SaleItem] PRIMARY KEY CLUSTERED ([saleID] ASC, [itemSKU] ASC),
CONSTRAINT [FK_SaleItem_Sales] FOREIGN KEY ([saleID]) REFERENCES [dbo].[Sales] ([saleID]),
CONSTRAINT [FK_SaleItem_Item] FOREIGN KEY ([itemSKU]) REFERENCES [dbo].[Item] ([ItemSKU])
);
I want to insert a new record into SaleItem table (the third one) where saleID is the last ID recorded in Sales table and ItemSKU which is equal to the value I get from another window.
I want these values:
SaleID = SELECT TOP 1 saleID FROM Sales ORDER BY saleID DESC";
ItemSKU = "SELECT itemName FROM Item WHERE ItemSKU = #sku";
I think I must do it in one query but I have no idea how.
Can you please give me a hint? I
First, you need to remove the IDENTITY property from the dbo.SaleItem table. The IDENTITY property is only required on the parent table, dbo.Sales.
You can do a single INSERT statement like this. It uses two subqueries, which are the SELECT statements in parentheses, to get values from the other two tables.
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = N'Widget'),
50);
You might want to turn it into a stored procedure, like this:
CREATE PROCEDURE dbo.up_InsertSaleItem
(
#itemName nvarchar(50),
#quantity int
)
AS
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = #itemName),
#quantity);
Then to use the stored procedure:
-- Test the stored procedure
EXEC dbo.up_InsertSaleItem #itemName=N'Widget', #quantity=50;
SELECT *
FROM dbo.SaleItem;
To read more about subqueries, see Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan, Chapter 4: Subqueries.

Oracle create table Invalid Name / Constraint

I met an error in an SQL command when trying to create a table in SQL. Below is my command:
CREATE TABLE Registration
(
registrationID varchar2(5) NOT NULL CONSTRAINT registrationID PRIMARY KEY,
competitionID varchar2(5) NOT NULL CONSTRAINT competitionID REFERENCES Competition(competitionID),
competitorID varchar2(5) NOT NULL CONSTRAINT competitorID REFERENCES Competitor(competitorID),
categoryType varchar2(6) NOT NULL,
entryFeeStatus char(1) NOT NULL,
creditCardNumber number(16),
datePaid date
);
My competitionID is primary key of Competition table.
My competitorID is primary key of Competitor table.
The error shown is:
Error report -
SQL Error: ORA-02264: name already used by an existing constraint
02264. 00000 - "name already used by an existing constraint"
*Cause: The specified constraint name has to be unique.
*Action: Specify a unique constraint name for the constraint.
May I know what I should change in my statement? Thank you.
Below are the Competition and Competitor tables that I created:
CREATE TABLE Competition
(
competitionID varchar2(5) NOT NULL CONSTRAINT competitionID PRIMARY KEY,
timePlanned date NOT NULL,
country varchar2(50) NOT NULL,
city varchar2(50),
address varchar2(50),
entryFee number(4) NOT NULL
);
CREATE TABLE Competitor
(
competitorID varchar2(5) NOT NULL CONSTRAINT competitorID PRIMARY KEY,
firstName varchar2(9) NOT NULL,
lastName varchar2(9) NOT NULL,
dateOfBirth date NOT NULL,
nationality varchar2(12),
gender varchar2(1) NOT NULL,
lifetimeRanking number(6),
totalPrizeMoney number(6)
);
You mixed up the two different ways to specify foreign keys. And had an extra comma.
CREATE TABLE Registration
(
registrationID varchar2(5) NOT NULL CONSTRAINT registrationID PRIMARY KEY,
competitionID varchar2(5) NOT NULL CONSTRAINT competitionIDfk REFERENCES Competition(competitionID),
competitorID varchar2(5) NOT NULL CONSTRAINT competitorIDfk REFERENCES Competitor(competitorID)
)
Foreign keys can either be specified per column:
columnname datatype CONSTRAINT constraintname REFERENCES tablename [ (column) ]
Or per table:
CONSTRAINT constraintname FOREIGN KEY (column-list) REFERENCES tablename [ (column-list) ]
BOOLEAN is not valid SQL type. Use NUMBER(1) with 0 and 1, CHAR(1) or VARCHAR2(1) with 'Y' and 'N' values or other surrogate representation.

Error while entering data into a table with Primary Key formed by multiple columns, each referenced from other tables

I have 4 tables, 3 of which have their own primary keys. In the 4th table, the primary keys of all the other 3 tables are referenced as foreign keys and these are made into a primary key (combination of all 3 foreign keys). However, upon entering data into the columns, I get constraint violation errors.
The code snippets are as below:
--Table # 1
create table PartSupplier(
partSupplierID int primary key,
fName varchar(20) NOT NULL,
lName varchar(20),
houseNO varchar(20),
streetName varchar(20),
city varchar(20),
dob date,
contactNo varchar(50)
)
--Table # 2
create table PartSpecialist(
partSpecialistID int primary key,
fName varchar(20) NOT NULL,
lName varchar(20),
houseNO varchar(20),
streetName varchar(20),
city varchar(20),
dob date,
contactNo varchar(15)
)
--Table # 3
create table CarPart(
partNumber int primary key,
description varchar (250),
vehicleID int NOT NULL,
imagePath varchar(50)
)
--Table # 4 (with multiple foreign keys made into one primary key)
create table SpecialistSuppliedPart(
partSpecialistID int NOT NULL,
partSupplierID int NOT NULL,
partNumber int NOT NULL,
condition varchar(10),
dateAcquired date,
costPrice int NOT NULL,
constraint specialist_supplier_part_PK primary key (partSpecialistID, partSupplierID, partNumber),
foreign key (partSpecialistID) references PartSpecialist(partSpecialistID),
foreign key (partSupplierID) references PartSupplier(partSupplierID),
foreign key (partNumber) references CarPart(partNumber)
)
I tried inserting the following values in the table:
3 3 5 USED 5000 2011-03-01
3 13 18 NEW 6000 2011-06-26
upon which I got the following error:
http://i.stack.imgur.com/HhFk2.jpg
where FK_SpecialistSuppliedPart_PartSupplier is the Foreign Key existing between Table # 1 and Table # 4.
I have all of these entries existing in the respective tables. After an exhaustive search on the internet (including stackoverflow.com), I could not find a solution.
What am I doing wrong here?
P.S. I tried adding the Foreign and Primary keys using MSSQLs Design Tool but it still results in the same error.

Check Constraint that references another table

Have a situation
2 different tables
CREATE TABLE albums(
album_id int identity (10,5) not null,
album_title varchar (40) not null,
album_itunes_price decimal DEFAULT 12.99 not null,
album_group_id int not null,
album_copies_sold int DEFAULT 0 null
)
go
CREATE TABLE SONGS
(song_id int identity (5,5) not null,
song_title varchar (50) not null,
song_group_id int not null,
song_album_id int null,
song_time time not null,
song_itunes_cost money not null )
GO
ALTER TABLE songs
ADD
CONSTRAINT pk_song_id
PRIMARY KEY (song_id),
CONSTRAINT fk_song_album_id
FOREIGN KEY (song_album_id)
REFERENCES albums(album_id),
CONSTRAINT fk_song_group_id
FOREIGN KEY (song_group_id)
REFERENCES groups(group_id)
go
create a check constraint on songs table called ck_songs_itunes_cost
The songs can be free but they can never be more than the album_itunes_price.
How do i create this constraint been working on it for 12 hours nothing is working.
I think the below is what you are expecting:
create a function that returns the values from album table:
Create function [dbo].[MaxValue]()
returns decimal
as
begin
declare #retval int
select #retval=MAX(album_itunes_price) from dbo.albums
return #retval
end;
Then create check constraint in songs which can get the value from albums table, because we can't use subquery in check constraint.
alter table dbo.songs
add constraint ck_songs_itunes_cost
check (songscolumn < dbo.MaxValue())
Make use of it based on your need.

Foreign key contraints in a table on two columns referncing a same table

I have a table Item master, in which i have a primary key as item code
tbl_item_master
Itm_code int PK
Bill of material(tbl_Bom)
child_id int
parent_id int
I have another table of bill of material(tbl_bom) in which there are 2 columns of parent and child which are having their values which is nothin but primary key of item master. I.e parent and child id in BOM are from Item Master's primary key. Follwoing is my script that I am using to apply foreign key on child and parent .
CREATE TABLE dbo.BOM_MASTER
(
BOM_SrNo INT CONSTRAINT DF_BOM_MASTER_BOM_SrNo DEFAULT ((0)) NOT NULL,
BOM_Key INT NOT NULL,
PD_Key INT,
BOM_Level INT,
BOM_Parent_Code VARCHAR (50),
BOM_Child_Code VARCHAR (50),
BOM_UOM INT,
BOM_Qty DECIMAL (14, 2),
BOM_Final_Version INT,
BOM_ItemDimension_Applicable BIT,
BOM_MatType INT CONSTRAINT DF__BOM_MASTE__BOM_M__192BAC54 DEFAULT ((0)) NOT NULL,
CONSTRAINT FK_BOM_MASTER_Project_Details_Master FOREIGN KEY (PD_Key) REFERENCES dbo.Project_Details_Master (PD_Key),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Parent_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Child_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code)
)
GO
and I am getting the following error
Cannot create two constraints named 'FK_BOM_MASTER_tbl_itm_master'. Duplicate constraint names are not allowed. Severity 16
If you add newlines, the issue becomes apparent.
CREATE TABLE dbo.BOM_MASTER
(
BOM_SrNo INT CONSTRAINT DF_BOM_MASTER_BOM_SrNo DEFAULT ((0)) NOT NULL,
BOM_Key INT NOT NULL,
PD_Key INT,
BOM_Level INT,
BOM_Parent_Code VARCHAR (50),
BOM_Child_Code VARCHAR (50),
BOM_UOM INT,
BOM_Qty DECIMAL (14, 2),
BOM_Final_Version INT,
BOM_ItemDimension_Applicable BIT,
BOM_MatType INT CONSTRAINT DF__BOM_MASTE__BOM_M__192BAC54 DEFAULT ((0)) NOT NULL,
CONSTRAINT FK_BOM_MASTER_Project_Details_Master FOREIGN KEY (PD_Key) REFERENCES dbo.Project_Details_Master (PD_Key),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Parent_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code),
CONSTRAINT FK_BOM_MASTER_tbl_itm_master FOREIGN KEY (BOM_Child_Code) REFERENCES tbl_itm_master (BSL_COST_ITEM_Item_SAP_Code)
)
GO
The last 2 are named identically. It is also clear there are other naming issues. What is DF__BOM_MASTE__BOM_M__192BAC54? Will future users of the table be able to gleem anything from this naming?

Resources