Trouble Referencing Two-part Primary Key in SQL Server - sql

I created this table with a two-part primary key:
Create Table Part
(PartNumber Int Not Null,
VendorNumber Int Not Null References Vendor(VendorNumber),
PartDescription VarChar(100) Not Null,
UnitPrice Money Not Null,
MTDSales Money Not Null,
YTDSales Money Not Null,
UnitsOnHand Int Not Null,
UnitsAllocated Int Not Null,
ReorderPoint Int Not Null,
VendorPrice Money Not Null,
MinimumOrderQuantity Int Not Null,
ExpectedLeadTime Datetime Not Null,
Primary Key (PartNumber, VendorNumber))
And another table is referencing the Part table's primary keys:
Create Table OrderDetail
(OrderNumber Int Not Null References Orders(OrderNumber),
SEQNumber Int Not Null,
PartNumber Int Not Null References Part(PartNumber),
VendorNumber Int Not Null References Part(VendorNumber),
NumberOrdered Int Not Null,
QuotedPrice Money Not Null,
LineTotal Int Not Null,
Comments VarChar(100) Not Null,
Primary Key (OrderNumber, SEQNumber))
When running the program, the following error is returned:
Msg 1776, Level 16, State 0, Line 99
There are no primary or candidate keys in the referenced table 'Part' that match the referencing column list in the foreign key 'FK__OrderDeta__PartN__239E4DCF'.
Could anyone provide suggestions on how to resolve the missing primary key error?

You need to create one composite foreign key, not two single-column keys. You can do it as a separate constraint in create table:
Create Table OrderDetail
(
OrderNumber Int Not Null References Orders(OrderNumber),
SEQNumber Int Not Null,
PartNumber Int Not Null,
VendorNumber Int Not Null,
NumberOrdered Int Not Null,
QuotedPrice Money Not Null,
LineTotal Int Not Null,
Comments VarChar(100) Not Null,
Primary Key (OrderNumber, SEQNumber),
constraint FK_OrderDetail_Part foreign key (PartNumber,VendorNumber)
references Part (PartNumber,VendorNumber)
)

Related

Problems referencing primary key with foreign key

This is code to create the beginnings of a book library database with Microsoft SQL Server Management Studio.
CREATE DATABASE BOOK_LIBRARY
CREATE TABLE LIBRARY_USER
(
usr_id int not null primary key,
f_name varchar(30) not null,
m_init char(1),
l_name varchar(30) not null,
balance decimal(6,2),
join_date date,
addrss_1 varchar(30) not null,
addrss_2 varchar(30),
city varchar(30) not null,
addrss_state char(2) not null,
zip_code varchar(10) not null,
email varchar(30)
);
CREATE TABLE LIBRARY_TRANSACTIONS
(
transaction_id int not null primary key,
maximum_borrow_duration int not null,
strt_date date not null,
actual_return_date date not null,
borrow_usr_id int not null,
foreign key (borrow_usr_id) references LIBRARY_USER(usr_id)
);
CREATE TABLE BOOKS
(
isbn varchar(17) not null primary key,
title varchar(30) not null,
number_of_copies int not null,
Author varchar(30) not null,
Number_of_pages int not null,
publish_year int not null,
book_type varchar(20)
);
CREATE TABLE DIGITAL_BOOKS
(
digital_id int not null primary key,
format varchar(30) not null,
size_mb int not null,
digital_isbn varchar(17) not null,
foreign key(digital_isbn) references BOOKS(isbn)
);
CREATE TABLE PHYSICAL_BOOKS
(
physical_id int not null primary key,
condition varchar(20) not null,
physical_isbn varchar(17) not null,
foreign key(physical_isbn) references BOOKS(isbn)
);
CREATE TABLE BOOK_COPY
(
digi_id int not null,
phys_id int not null,
primary key(digi_id, phys_id),
foreign key(digi_id) references DIGITAL_BOOKS(digital_id),
foreign key(phys_id) references PHYSICAL_BOOKS(physical_id)
);
CREATE TABLE CONTNS
(
trans_id int not null primary key,
digi_id int not null,
phys_id int not null,
foreign key(digi_id) references BOOK_COPY(digi_id),
foreign key(phys_id) references BOOK_COPY(phys_id)
);
Despite me being able to look and see that digi_id and phys_id are in fact primary keys of the book_copy table, I keep getting this error:
Msg 1776, Level 16, State 0, Line 66
There are no primary or candidate keys in the referenced table 'BOOK_COPY' that match the referencing column list in the foreign key 'FK__CONTNS__digi_id__37A5467C'.
Msg 1750, Level 16, State 1, Line 66
Could not create constraint or index. See previous errors.
Am I missing something obvious? I'm just starting out with using this program, so any help is greatly appreciated.
Here:
CREATE TABLE CONTNS
(
trans_id int not null primary key,
digi_id int not null,
phys_id int not null,
foreign key(digi_id) references BOOK_COPY(digi_id),
foreign key(phys_id) references BOOK_COPY(phys_id)
);
You are creating two foreign keys to parent table BOOK_COPY. But that table has a compound primary key (ie a multi-column primary key)
CREATE TABLE BOOK_COPY
(
digi_id int not null,
phys_id int not null,
primary key(digi_id, phys_id), --> here
...
)
As a consequence, you need a compound foreign key:
CREATE TABLE CONTNS
(
trans_id int not null primary key,
digi_id int not null,
phys_id int not null,
foreign key(digi_id, phys_id) references BOOK_COPY(digi_id, phys_id)
);

Key column does not exist in table. SQL

So I tried looking up other questions and tried them, but I was not able to figure out why my SQL was not working. It keeps saying that DepartmentID table does not exist and I have it declared as my primary key under Department.
CREATE TABLE EMPLOYEE(
SSN INT NOT NULL,
WorkID INT NOT NULL,
BirthDate DATE NOT NULL,
Name VARCHAR(20) NOT NULL,
UNIQUE(WorkID),
PRIMARY KEY(SSN),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
FOREIGN KEY(DeviceID) REFERENCES DEVICE(DeviceID)
);
CREATE TABLE DEPARTMENT(
DepartmentID INT NOT NULL,
DepartmentName VARCHAR (20) NOT NULL,
PRIMARY KEY(DepartmentID),
UNIQUE(DepartmentName)
);
CREATE TABLE PRODUCT(
ProductID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
Isle VARCHAR(5) NOT NULL,
Company VARCHAR(20) NOT NULL,
PRIMARY KEY(ProductID),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID)
);
CREATE TABLE DEVICE(
DeviceID INT NOT NULL,
DateReceived DATE NOT NULL,
PRIMARY KEY(DeviceID)
);
CREATE TABLE SALES(
SalesID INT NOT NULL,
Profit INT NOT NULL,
Revenue INT NOT NULL,
PRIMARY KEY(SalesID)
);
CREATE TABLE AmountSold(
FOREIGN KEY (SalesID) REFERENCES SALES(SalesID),
FOREIGN KEY (ProductID) REFERENCES PRODUCT(ProductID)
);
The problem was that you were making foreign key but the column DepartmentID
doesn't exist on that table in which you were referencing and the second was
that your order wasn't correct.
CREATE TABLE DEPARTMENT(
DepartmentID INT NOT NULL,
DepartmentName VARCHAR (20) NOT NULL,
PRIMARY KEY(DepartmentID),
UNIQUE(DepartmentName)
);
CREATE TABLE DEVICE(
DeviceID INT NOT NULL,
DateReceived DATE NOT NULL,
PRIMARY KEY(DeviceID)
);
CREATE TABLE EMPLOYEE(
SSN INT NOT NULL,
WorkID INT NOT NULL,
BirthDate DATE NOT NULL,
DepartmentID INT NOT NULL,
DeviceID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
UNIQUE(WorkID),
PRIMARY KEY(SSN),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
FOREIGN KEY(DeviceID) REFERENCES DEVICE(DeviceID)
);
CREATE TABLE PRODUCT(
ProductID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
DepartmentID INT NOT NULL,
Isle VARCHAR(5) NOT NULL,
Company VARCHAR(20) NOT NULL,
PRIMARY KEY(ProductID),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID)
);
CREATE TABLE SALES(
SalesID INT NOT NULL,
Profit INT NOT NULL,
Revenue INT NOT NULL,
PRIMARY KEY(SalesID)
);
CREATE TABLE AmountSold(
FOREIGN KEY (SalesID) REFERENCES SALES(SalesID),
FOREIGN KEY (ProductID) REFERENCES PRODUCT(ProductID)
);
The problem here you didn't declared the DepartmentId column in Employee table. Also execute the parent table first followed by the ones referring
CREATE TABLE DEPARTMENT(
DepartmentID INT NOT NULL,
DepartmentName VARCHAR (20) NOT NULL,
PRIMARY KEY(DepartmentID)
);
CREATE TABLE DEVICE(
DeviceID INT NOT NULL,
DateReceived DATE NOT NULL,
PRIMARY KEY(DeviceID)
);
CREATE TABLE EMPLOYEE(
SSN INT NOT NULL,
WorkID INT NOT NULL,
BirthDate DATE NOT NULL,
Name VARCHAR(20) NOT NULL,
DepartmentID INT,
DeviceID INT ,
UNIQUE(WorkID),
PRIMARY KEY(SSN),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
FOREIGN KEY(DeviceID) REFERENCES DEVICE(DeviceID)
);
CREATE TABLE PRODUCT(
ProductID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
Isle VARCHAR(5) NOT NULL,
Company VARCHAR(20) NOT NULL,
DepartmentID INT,
PRIMARY KEY(ProductID),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID)
);
CREATE TABLE SALES(
SalesID INT NOT NULL,
Profit INT NOT NULL,
Revenue INT NOT NULL,
PRIMARY KEY(SalesID)
);
CREATE TABLE AmountSold(
SalesId INT NOT NULL,
ProductId INT NOT NULL,
FOREIGN KEY (SalesID) REFERENCES SALES(SalesID),
FOREIGN KEY (ProductID) REFERENCES PRODUCT(ProductID)
);

How to Relate 2 table with each other with 2 foreign keys

Here is my code it generates Foreign key conflict error
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NOT NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NOT NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
You cannot do that. This is a circular reference.
This is a bad design but if you want to do that, you need to make foreign key columns Nullable.
CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)
CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)
Then you need to update reference fields after inserting records in tblBatches and tblProducts.
The good design says you need to create a bridge table like this:
CREATE TABLE tblProductsBatch
(
ID int NOT NULL IDENTITY PRIMARY KEY,
ProductID int NOT NULL,
BatchID int NOT NULL
)
And after inserting product and batch, you need to insert a record in this table to link rows to each other.

Error relate SQL Server tables

I have the following problem: when we run the code, it displays the following error:
There are primary keys or candidates in the reference Ticket table
that match the list of referencing columns in foreign key '
FK__Payment__PkTicke__1A14E395
Code:
create table SystemUser
(
PkUser int identity(1,1),
UserLogin nvarchar(20) not null unique,
UserPassword nvarchar(50) not null,
UserName nvarchar(50) not null,
UserCpf nvarchar(50) not null,
UserBirth datetime not null,
UserGender nvarchar(15) not null,
AddressCep int not null,
AddressStreet nvarchar(50) not null,
AddressNumber nvarchar(20) not null,
AddressComplement nvarchar(50) not null,
AddressCity nvarchar(50) not null,
AddressState nvarchar(50) not null,
primary key(PkUser)
)
create table Attractions
(
PkAttraction integer identity(1,1) ,
AttractionName nvarchar(50) not null unique,
AttractionDate datetime not null,
AttractionDescription nvarchar(150) not null
primary key(PkAttraction)
)
create table Ticket
(
PkTicket int identity(1,1),
PkUser int not null,
PkAttraction int not null,
TicketPrice decimal not null,
primary key(PkTicket, PkUser, PkAttraction),
foreign key(PkUser) references SystemUser(PkUser),
foreign key(PkAttraction) references Attractions(PkAttraction)
)
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
foreign key(PkTicket) references Ticket(PkTicket),
)
create table FormPayment
(
PkFromPayment int identity(1,1),
PkPayment int not null,
ShareValue decimal not null,
ExpirationDate datetime not null
primary key(PkFromPayment, PkPayment),
foreign key(PkPayment) references Payment(PkPayment),
)
Your Ticket table as a primary key made up from 3 columns:
create table Ticket
(
.....
primary key(PkTicket, PkUser, PkAttraction),
....
)
Any table that wants to reference that table Ticket must also provide all 3 columns for the foreign key.
You cannot reference only part of a primary key - if you want to reference it, you must have all columns that it contains - otherwise you cannot establish a FK relationship.
So you must add the PkUser and PkAttraction columns to your Payment table so that you can establish this FK relationship:
create table Payment
(
PkPayment int identity(1,1),
PkTicket int not null,
PkUser int not null, // add this
PkAttraction int not null, // add this
Portion int not null,
IdTransaction nvarchar(100) not null,
Payday datetime not null,
primary key(PkPayment, PkTicket),
// change to this
foreign key(PkTicket, PkUser, PkAttraction) references Ticket(PkTicket, PkUser, PkAttraction)
.....
)
When you not specify a name for FK and PK, SQL server generates a name. in this case, looks like SQL server generates duplicate name.
If you specify name for FK and PK, it will work.

SQL - Cannot add foreign key constraint

I am completely new to writing SQL code and I am attempting to run a simple table creation, however I cannot find where the error in my programming is, and as I am completely new I am struggling with this creation.
This is a school project that I am working on, and hoping anyone can help.
The error I am receiving in 'SQLFiddle' is "Cannot add foreign key constraint" on the following code:
CREATE TABLE invoice(
invoice_id INT NOT NULL,
customer_id INT NOT NULL,
order_date DATE NULL,
spec_order_note VARCHAR(45) NULL,
PRIMARY KEY(invoice_id, customer_id),
FOREIGN KEY (customer_id)
REFERENCES customer.customer_id
ON DELETE CASCADE
ON UPDATE CASCADE
);
CREATE TABLE line_item (
invoice_id INT NOT NULL,
donut_id INT NOT NULL,
quantity INT NULL
CONSTRAINT donut_invoice
FOREIGN KEY invoice_id
REFERENCES invoice.invoice_id
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
CREATE TABLE donut (
donut_id INT NOT NULL,
donut_name VARCHAR(15) NULL,
description VARCHAR(30) NULL,
unit_price INT NULL
PRIMARY KEY(donut_id),
)
CREATE TABLE customer (
customer_id INT NOT NULL,
last_name VARCHAR(15) NULL,
first_name VARCHAR(10) NULL,
street_add VARCHAR(20) NULL,
apt_num INT NULL,
city VARCHAR(20) NULL,
state VARCHAR(15) NULL,
zip_code INT NULL,
home_phone VARCHAR(10) NULL,
mobile_phone VARCHAR(10) NULL,
other_phone VARCHAR(10) NULL,
customer_notes VARCHAR(45) NULL
PRIMARY KEY(customer_id),
)
Any help is greatly appreciated.
You can only reference existing tables and columns in foreign constraints. So if you want to reference customer table in invoice's foreign key, you need to either create customer before invoice or add the foreign key constrain additionally using ALTER TABLE.
Apart of that, there's couple syntax errors in your code like missing semicolons and misplaced (missing and additional) commas.
A working code:
CREATE TABLE customer (
customer_id INT NOT NULL,
last_name VARCHAR(15) NULL,
first_name VARCHAR(10) NULL,
street_add VARCHAR(20) NULL,
apt_num INT NULL,
city VARCHAR(20) NULL,
state VARCHAR(15) NULL,
zip_code INT NULL,
home_phone VARCHAR(10) NULL,
mobile_phone VARCHAR(10) NULL,
other_phone VARCHAR(10) NULL,
customer_notes VARCHAR(45) NULL,
PRIMARY KEY(customer_id)
);
CREATE TABLE invoice(
invoice_id INT NOT NULL,
customer_id INT NOT NULL,
order_date DATE NULL,
spec_order_note VARCHAR(45) NULL,
PRIMARY KEY(invoice_id, customer_id),
FOREIGN KEY (customer_id)
REFERENCES customer (customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
CREATE TABLE line_item (
invoice_id INT NOT NULL,
donut_id INT NOT NULL,
quantity INT NULL,
CONSTRAINT donut_invoice
FOREIGN KEY (invoice_id)
REFERENCES invoice (invoice_id)
ON DELETE RESTRICT
ON UPDATE RESTRICT
);
CREATE TABLE donut (
donut_id INT NOT NULL,
donut_name VARCHAR(15) NULL,
description VARCHAR(30) NULL,
unit_price INT NULL,
PRIMARY KEY(donut_id)
);
http://sqlfiddle.com/#!9/36b044