Azure SQL Foreign Key with Visual Studio 2015 - sql

I have an Azure SQL database created in the management station, I connect to it on Visual Studio 2015, I create tables Player and Team, I'm trying to create a foreign key to reference team name but I keep getting the following error;
SQL71516 :: The referenced table '[dbo].[Team]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
From looking at online sources, mainly MSDN, I have tried a few ways to solve this issue but have had no luck. Here is my SQL code;
Team Table:
CREATE TABLE [dbo].[Team] (
[Id] INT NOT NULL,
[Name] VARCHAR (30) NOT NULL,
[Wins] INT NOT NULL,
[Draws] INT NOT NULL,
[Losses] INT NOT NULL,
[GoalsFor] INT NOT NULL,
[GoalsAgainst] INT NOT NULL,
[GoalDifference] INT NOT NULL,
[Points] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Player Table:
CREATE TABLE [dbo].[Player] (
[Id] INT NOT NULL,
[Name] VARCHAR (30) NOT NULL,
[Team] VARCHAR (30) NOT NULL,
[Goals] INT NOT NULL,
[Assists] INT NOT NULL,
[Apps] INT NOT NULL,
[Club] VARCHAR (30) NOT NULL,
CONSTRAINT [FK_Player_Club] FOREIGN KEY ([Club]) REFERENCES [dbo].[Team]([Name]),
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Team Table:
CREATE TABLE [dbo].[Team] (
[Id] INT NOT NULL,
[Name] VARCHAR (30) NOT NULL,
[Wins] INT NOT NULL,
[Draws] INT NOT NULL,
[Losses] INT NOT NULL,
[GoalsFor] INT NOT NULL,
[GoalsAgainst] INT NOT NULL,
[GoalDifference] INT NOT NULL,
[Points] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Player Table:
CREATE TABLE [dbo].[Player] (
[Id] INT NOT NULL,
[Name] VARCHAR (30) NOT NULL,
[Team] VARCHAR (30) NOT NULL,
[Goals] INT NOT NULL,
[Assists] INT NOT NULL,
[Apps] INT NOT NULL,
[TeamId] INT NOT NULL,
CONSTRAINT [FK_Player_Club] FOREIGN KEY ([TeamId]) REFERENCES [dbo].[Team]([Id]),
PRIMARY KEY CLUSTERED ([Id] ASC)
);

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

Can a value be a primary and a foreign key?

I have the following tables in my SQL Server database.
Customer is a subtype of User thus I made a reference from Customer to User.
I also want to link my customer to my reservation. I'd like to use the Foreign key in the Customer table as a PK for this relation. When I write this out in SQL Server, I get this error under "(userid)":
Invalid column 'userid'
How can I make this relation?
Create table [dbo].[User]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[name] varchar(50) NOT NULL,
[password] nvarchar(100) NOT NULL,
)
Create table [dbo].[Customer]
(
[userid] int FOREIGN KEY REFERENCES [dbo].[User](id) NOT NULL,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
)
Create table [dbo].[Reservation]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[datum] date NOT NULL,
[prijs] decimal NOT NULL,
[levertijd] datetime NOT NULL,
[ophaaltijd] datetime NOT NULL,
[leverAdres] varchar(60) NOT NULL,
[klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](userid) NOT NULL
)
yes this is possible, try it like this
Create table [dbo].[Customer]
(
[userid] int not null,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
constraint PK_UserID primary key ([userid]),
constraint FK_Customer_User foreign key (userid) references [User] (id)
)
But I have to say that userid seems like an odd primary key for a table called Customer
I would so something like this :
Create table [dbo].[Customer]
(
[CustomerID] int not null identity,
[userid] int not null,
[street] varchar(40) NOT NULL,
[housenumber] varchar(10) NOT NULL,
[postalcode] varchar(10) NOT NULL,
[phonenumber] varchar(20) NOT NULL,
[email] varchar(30) NOT NULL,
constraint PK_CustomerID primary key ([CustomerID]),
constraint FK_Customer_User foreign key (userid) references [User] (id)
)
Create table [dbo].[Reservation]
(
[id] int PRIMARY KEY IDENTITY (1,1) NOT NULL,
[datum] date NOT NULL,
[prijs] decimal NOT NULL,
[levertijd] datetime NOT NULL,
[ophaaltijd] datetime NOT NULL,
[leverAdres] varchar(60) NOT NULL,
[klantId] int FOREIGN KEY REFERENCES [dbo].[Customer](customerid) NOT NULL
)

Movie Ticket System (DB)

I'm making a online movie reservation system on MVC and I am stuck at the database part on how the tables would link to each other. Does it seem alright?
ERD
CREATE TABLE [dbo].[Member]
(
[memberID] INT IDENTITY (1, 1) NOT NULL,
[memFirstName] VARCHAR (50) NULL,
[memLastName] VARCHAR (50) NULL,
[memEmailAddress] VARCHAR (50) NULL,
[memPassword] VARCHAR (15) NULL,
[memTelephone] CHAR (10) NULL,
[memAddress] VARCHAR (70) NULL,
PRIMARY KEY CLUSTERED ([memberID] ASC)
);
CREATE TABLE [dbo].[Movie]
(
[movieID] INT IDENTITY (1, 1) NOT NULL,
[movieName] VARCHAR (100) NULL,
[movieCategory] CHAR (10) NULL,
PRIMARY KEY CLUSTERED ([movieID] ASC)
);
CREATE TABLE [dbo].[Reservation]
(
[resID] INT IDENTITY (1, 1) NOT NULL,
[memberID] INT NOT NULL,
[showID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([resID] ASC),
FOREIGN KEY ([memberID]) REFERENCES [dbo].[Member] ([memberID]),
FOREIGN KEY ([showID]) REFERENCES [dbo].[Show] ([showID])
);
CREATE TABLE [dbo].[Show]
(
[showID] INT IDENTITY (1, 1) NOT NULL,
[showDateTime] DATETIME NOT NULL,
[movieID] INT NULL,
CONSTRAINT [PK_Show] PRIMARY KEY CLUSTERED ([showID] ASC),
FOREIGN KEY ([showID]) REFERENCES [dbo].[Movie] ([movieID])
);

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.

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