Can a value be a primary and a foreign key? - sql

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
)

Related

SQL71501 :: Foreign Key: [dbo].[FK_AddressBook_Country] has an unresolved reference to Column [dbo].[AddressBook].[CountryID]

hope someone can help me. I have an error
" SQL71501 :: Foreign Key: [dbo].[FK_AddressBook_Country] has an unresolved reference to Column [dbo].[AddressBook].[CountryID]. "
It red line the ([CountryID)]. I can't find where its fault. I actually followed this site http://demo.dotnetawesome.com/mvc/mycontactbook/part2 , I just changed the tables. Hopefully, someone can help me with this. Thank you so much!
CREATE TABLE [dbo].[AddressBook] (
[Id] INT NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Surname] VARCHAR (50) NOT NULL,
[Address1] VARCHAR (200) NOT NULL,
[Address2] VARCHAR (100) NULL,
[Postcode] VARCHAR (6) NOT NULL,
[Town] VARCHAR (20) NOT NULL,
[Country] VARCHAR (50) NOT NULL,
[Email] VARCHAR (50) NOT NULL,
[MobileNumber] VARCHAR (20) NOT NULL,
[PictureUser] VARCHAR (200) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_AddressBook_Country] FOREIGN KEY ([CountryID]) REFERENCES [Country]([CountryID])
);
CREATE TABLE [dbo].[Country] (
[CountryID] INT IDENTITY (1, 1) NOT NULL,
[CountryName] VARCHAR (100) NOT NULL,
PRIMARY KEY CLUSTERED ([CountryID] ASC)
);
this should work fine how ever there are two mistakes first in "FOREIGN KEY ([CountryID])" you have no field in the AdresseBook named "CountryId" i think you wanted the field "Country" as a foreign key if this is the case the the Country field in adressBook must have the same type with CountryID of the table Country
CREATE TABLE [dbo].[AddressBook] (
[Id] INT NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Surname] VARCHAR (50) NOT NULL,
[Address1] VARCHAR (200) NOT NULL,
[Address2] VARCHAR (100) NULL,
[Postcode] VARCHAR (6) NOT NULL,
[Town] VARCHAR (20) NOT NULL,
[Country] INT NOT NULL,
[Email] VARCHAR (50) NOT NULL,
[MobileNumber] VARCHAR (20) NOT NULL,
[PictureUser] VARCHAR (200) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_AddressBook_Country] FOREIGN KEY ([Country]) REFERENCES [Country]([CountryID])
);
CREATE TABLE [dbo].[Country] (
[CountryID] INT IDENTITY (1, 1) NOT NULL,
[CountryName] VARCHAR (100) NOT NULL,
PRIMARY KEY CLUSTERED ([CountryID] ASC)
);

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

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

Azure SQL Foreign Key with Visual Studio 2015

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

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.