Error relate SQL Server tables - sql

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.

Related

Foreign key references invalid column error

I'm trying to run this query but SQL -erver stopped me with this error:
Foreign key 'FK__food__groupid__3F115E1A' references invalid column 'groupid' in referenced table 'sub'.
This is my query:
create table menu
(
valedid int primary key not null,
name nvarchar(50) not null,
)
create table sub
(
qroupid int primary key not null,
groupname nvarchar(50) not null,
valedid int not null,
foreign key(valedid) references menu (valedid),
)
create table food
(
foodid int primary key not null,
radif int identity(1,1) not null,
qeymat int not null,
name nvarchar(100) not null,
groupid int not null,
foreign key(groupid) references sub(groupid),
)
You create the column with name qroupid and not groupid in table sub

SQL Server trigger updating other table based on the table with the trigger

I'm a newbie in SQL and I want to ask a specific question about the triggers. I have a table Purchases and I want to make an update to an other table with the same ID
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases
AFTER INSERT
AS
BEGIN
UPDATE EmployeesSalary
SET MonthlySalesMade = MonthlySalesMade + 1
WHERE EmployeeID = (SELECT DealMadeByEmployeeID FROM inserted)
END
based on the current inserted row.
But it doesn't seem to work (I don't get any errors).
My database
CREATE DATABASE RealEstateDatabase;
GO
USE RealEstateDatabase;
GO
CREATE TABLE Employees
(
EmployeeID INT IDENTITY NOT NULL PRIMARY KEY,
FirstName NVARCHAR(25) NOT NULL,
SecondName NVARCHAR(25) NOT NULL,
LastName NVARCHAR(25) NOT NULL,
NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
PhoneNumber NVARCHAR(20) NOT NULL,
Email NVARCHAR(50) NOT NULL,
[Address] NVARCHAR(50) NOT NULL,
CONSTRAINT UC_EmployeesNIN UNIQUE (NIN)
);
GO
CREATE TABLE GivingClients -- отдаващи клиенти(наемодатели и продавачи)
(
ClientID INT IDENTITY NOT NULL PRIMARY KEY,
ClientType NVARCHAR(20) NOT NULL,--Leaser(наемодател) or Seller
FirstName NVARCHAR(25) NOT NULL,
SecondName NVARCHAR(25),
LastName NVARCHAR(25) NOT NULL,
NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
PhoneNumber NVARCHAR(20) NOT NULL,
Email NVARCHAR(50),
[Town/Village] NVARCHAR(20),
[Address] NVARCHAR(50),
ServedByEmployeeID INT NOT NULL, -- по EmployeeID
CONSTRAINT FK_GivingClients_Employees
FOREIGN KEY (ServedByEmployeeID) REFERENCES Employees(EmployeeID),
CONSTRAINT CHK_GivingClients CHECK (ClientType IN('наемодател','продавач'))-- наемодател или продавач
);
GO
CREATE TABLE TakingClients -- приемащи клиенти (наематели и купувачи)
(
ClientID INT IDENTITY NOT NULL PRIMARY KEY,
ClientType NVARCHAR(20) NOT NULL,
FirstName NVARCHAR(25) NOT NULL,
SecondName NVARCHAR(25),
LastName NVARCHAR(25) NOT NULL,
NIN NVARCHAR(30) NOT NULL,--National Identification Number (ЕГН)
PhoneNumber NVARCHAR(20) NOT NULL,
Email NVARCHAR(50),
[Town/Village] NVARCHAR(20),
[Address] NVARCHAR(50),
ServedByEmployeeID INT NOT NULL, -- по EmployeeID
ServedByGivingClientID INT, -- връзка към отдаващите клиенти
CONSTRAINT FK_TakingClients_Employees
FOREIGN KEY (ServedByEmployeeID) REFERENCES Employees(EmployeeID),
CONSTRAINT FK_TakingClients_GivingClients
FOREIGN KEY (ServedByGivingClientID) REFERENCES GivingClients(ClientID),
CONSTRAINT CHK_TakingClients CHECK (ClientType IN('наемател', 'купувач'))
);
GO
CREATE TABLE EstatesBasicInfo
(
RealEstateID INT IDENTITY NOT NULL PRIMARY KEY,
RealEstateType NVARCHAR(20) NOT NULL,--бизнес имот, къща, апартамент, гараж
Area NVARCHAR(25) NOT NULL,--в квадратни метри
Architecture NVARCHAR(30), --панел, тухла и т.н.
Photos IMAGE,
OfferedByEmployeeID INT NOT NULL,
[OwnerID] INT NOT NULL,
CONSTRAINT FK_EstatesBasicInfo_GivingClients
FOREIGN KEY ([OwnerID]) REFERENCES GivingClients(ClientID),
CONSTRAINT FK_EstatesBasicInfo_Employees
FOREIGN KEY (OfferedByEmployeeID) REFERENCES Employees(EmployeeID)
);
GO
CREATE TABLE EstatesLocation
(
RealEstateLocationID INT NOT NULL PRIMARY KEY,
Country NVARCHAR(50) NOT NULL,
Region NVARCHAR(50) NOT NULL, --Област
[Town/Village] NVARCHAR(50) NOT NULL,
[Address] NVARCHAR(50) NOT NULL,
CONSTRAINT FK_EstatesLocation_EstatesBasicInfo
FOREIGN KEY (RealEstateLocationID) REFERENCES EstatesBasicInfo(RealEstateID)
);
GO
CREATE TABLE EstatesDetails
(
RealEstateDetailsID INT NOT NULL PRIMARY KEY,
Position NVARCHAR(11) NOT NULL,--изток, запад, север, юг, югоизток, югозапад, североизток, северозапад
Conditions NVARCHAR(15) NOT NULL, --добри или лоши
[Floor] INT NOT NULL, --етажът на който се намира или колко етажа има (в зависимост от видът на обекта)
Rooms INT NOT NULL,
CONSTRAINT CHK_EstateDetails CHECK (Position IN('изток', 'запад', 'север', 'юг', 'югоизток', 'югозапад', 'североизток', 'северозапад', 'всички') AND [Floor]>=0 AND Rooms>0),
CONSTRAINT FK_EstatesDetails_EstatesLocation
FOREIGN KEY (RealEstateDetailsID) REFERENCES EstatesLocation(RealEstateLocationID)
);
GO
CREATE TABLE EmployeesSalary
(
EmployeeID INT NOT NULL PRIMARY KEY,
CurrentSalary MONEY DEFAULT 0,-- на процент
MonthlySalesMade INT DEFAULT 0,
MonthlyRentsMade INT DEFAULT 0,
CONSTRAINT FK_EmployeesSalary_Employees
FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID),
CONSTRAINT CHK_EmployeesSalary
CHECK (CurrentSalary>=0 AND MonthlySalesMade>=0 AND MonthlyRentsMade>=0)
);
GO
CREATE TABLE Purchases
(
PurchaseID INT IDENTITY NOT NULL PRIMARY KEY,
DateBought SMALLDATETIME NOT NULL,
Price MONEY NOT NULL CHECK (Price>0),
RealEstateID INT UNIQUE NOT NULL,
DealMadeByEmployeeID INT NOT NULL,
CONSTRAINT FK_Purchases_EstatesBasicInfo
FOREIGN KEY (RealEstateID) REFERENCES EstatesBasicInfo(RealEstateID),
CONSTRAINT FK_Purchases_Employees
FOREIGN KEY (DealMadeByEmployeeID) REFERENCES Employees(EmployeeID)
);
GO
CREATE TABLE Rents
(
RentID INT IDENTITY NOT NULL PRIMARY KEY,
StartDate SMALLDATETIME,
EndDate SMALLDATETIME,
Price MONEY,
RealEstateID INT UNIQUE NOT NULL,
DealMadeByEmployeeID INT NOT NULL,
CONSTRAINT CHK_Rents CHECK (Price > 0 AND EndDate > StartDate),
CONSTRAINT FK_Rents_EstatesBasicInfo
FOREIGN KEY (RealEstateID) REFERENCES EstatesBasicInfo(RealEstateID),
CONSTRAINT FK_Rents_Employees
FOREIGN KEY (DealMadeByEmployeeID) REFERENCES Employees(EmployeeID)
);
Your trigger should work for a single insert. It is safer to write using IN:
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases AFTER INSERT
AS
BEGIN
UPDATE EmployeesSalary
SET MonthlySalesMade = MonthlySalesMade + 1
WHERE EmployeeID IN (SELECT DealMadeByEmployeeID FROM inserted)
END;
Or using JOIN:
CREATE TRIGGER tr_EmployeesSalaryPurchasesUpdate
ON Purchases AFTER INSERT
AS
BEGIN
UPDATE es
SET MonthlySalesMade = es.MonthlySalesMade + 1
FROM EmployeesSalary es JOIN
inserted i
ON es.EmployeeID = i.DealMadeByEmployeeID
END;
Note: If MonthlySalesMade is initialized to NULL rather than 0, then the expression should take the NULL into account:
SET MonthlySalesMade = COALESCE(es.MonthlySalesMade + 1, 1)

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

Trouble Referencing Two-part Primary Key in SQL Server

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)
)

Microsoft SQL, foreign key not referencing table, can't see what's causing it

I've spent a while trying to firgure it but but I can't see anything that would be causing this error. I'm thinking maybe something to do with the "Unique" statement.
Msg 1767, Level 16, State 0, Line 40
Foreign key 'FK_Loan_ItemNo__0AD2A005' references invalid table
'Item'.
Here's the code if someone wants to use it to replicate problem:
CREATE DATABASE LibrarySystem10
GO
USE LibrarySystem10
GO
CREATE TABLE MemberType(
MemberTypeNo int NOT NULL,
Name varchar(50) NOT NULL,
Description varchar(250) NOT NULL,
MaxNumberLoans int NOT NULL,
MaxLoanDuration int NOT NULL
PRIMARY KEY (MemberTypeNo)
)
insert into MemberType values ('0','UnderGraduate','A student at a college or university who has not yet earned a bachelor''s or equivalent degree.','5','10')
insert into MemberType values ('1','PostGraduate','A student undertaking study after completing a first degree.','10','10')
insert into MemberType values ('2','Staff','Staff at the university','15','15')
CREATE TABLE Member(
MemberNo int NOT NULL,
MemberTypeNo int NOT NULL,
FirstName varchar(150) NOT NULL,
LastName varchar(150) NULL,
DateOfBirth varchar (200) NULL,
HouseNo int NOT NULL,
Street varchar(50) NOT NULL,
Suburb varchar(100) NOT NULL,
PostCode int NOT NULL,
EmailAddress varchar(250) NULL,
HomePhoneNo varchar(250) NULL,
MobileNo varchar(250) NULL,
MembershipStartDate varchar (200) NOT NULL,
MembershipEndDate varchar (200) NOT NULL,
MembershipStatus varchar(100) NOT NULL,
PinNo int NOT NULL
PRIMARY KEY (MemberNo)
FOREIGN KEY (MemberTypeNo)REFERENCES MemberType ON UPDATE CASCADE
)
insert into member values ('0','0','Shane','Lindsay','15-11-1992','90','fake st','FauxTon','2250','shane#hotmai.com','0243296356','0415657164','15-11-2010','15-11-2020','current','0105')
insert into member values ('1','0','Shaune','Lincoln','18-12-1992','92','faken st','FauxTone','2350','shaune27#hotmai.com','0243253357','041565757','14-12-2010','14-12-2020','deferred','0123')
insert into member values ('2','0','Sarah','richards','08-08-1990','45','Small st','Hornsby','2279','Sarah67#hotmai.com','02432567154','0416451845','01-01-2012','01-01-2022','current','0123')
CREATE TABLE Loan(
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
ItemNo int NOT NULL FOREIGN KEY(ItemNo) REFERENCES Item ON UPDATE CASCADE,
DateLoaned varchar (50) NOT NULL,
DueDate varchar (50) NOT NULL,
Status varchar(50) NOT NULL,
FinesImposed bit NOT NULL DEFAULT '0' CHECK (finesImposed IN ('0','1')) ,
Renewed bit NOT NULL DEFAULT '0' CHECK (Renewed IN ('0','1')),
UNIQUE(MemberNo,ItemNo,DateLoaned)
)
insert into Loan values ('0','0','10-10-2012','15-10-2012','loaned','0','0')
insert into Loan values ('1','0','12-10-2012','15-10-2012','loaned','0','1')
CREATE TABLE Item(
ItemNo int NOT NULL,
Title varchar(50) NOT NULL,
Subject varchar(100) NULL,
ISBN int NULL,
PhysicalDescription varchar(150) NULL,
Author varchar(75) NULL,
PRIMARY KEY (ItemNo)
)
insert into Item values ('0','Book1','IT','0501425252','Big,42pages','John Doe')
insert into Item values ('1','Book2','IT','0501425253','Big,42pages','John Doe')
CREATE TABLE ItemCopy(
ItemNo int NOT NULL,
CallNumber varchar(50) NOT NULL,
Condition varchar(50) NULL,
UNIQUE(ItemNo,CallNumber),
PRIMARY KEY (CallNumber)
)
insert into ItemCopy values ('0','0','good')
CREATE TABLE Hold(
HoldNo int NOT NULL,
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
ItemNo int NOT NULL FOREIGN KEY(ItemNo) REFERENCES Item ON UPDATE CASCADE,
DateTimeHeld datetime NOT NULL,
comments varchar(200) NULL,
Status varchar(50) NOT NULL
PRIMARY KEY (HoldNo)
)
CREATE TABLE Fine(
FineNo int NOT NULL,
MemberNo int NOT NULL FOREIGN KEY(MemberNo) REFERENCES Member ON UPDATE CASCADE,
Description varchar(50) NULL,
Amount int NOT NULL,
PRIMARY KEY (FineNo)
)
CREATE TABLE AudioRecording(
Length varchar(50) NULL,
BitRate varchar(50) NULL,
Size varchar(50) NULL
)
CREATE TABLE ItemCollection(
ItemNo int NULL,
CollectionName varchar(75) NULL
UNIQUE (ItemNo,CollectionName)
)
CREATE TABLE Collection(
CollectionName varchar(75)NOT NULL
PRIMARY KEY (CollectionName)
)
CREATE TABLE Book(
PublisherInfo varchar(150) NULL,
Edition int NULL,
Notes varchar(250) NULL,
Status varchar(50) NULL
)
CREATE TABLE Journal(
Series int NULL,
Notes varchar(250) NULL,
OtherTitles varchar(150) NULL,
PriorTitles varchar(250) NULL
)
SELECT m.FirstName, l.Status, l.DueDate
FROM Member m, Loan l
WHERE m.MemberNo = '0' AND l.MemberNo = m.MemberNo
Loan references Item, but you create Loan before you create Item. Create the Item table first.