Creating all database 'things' in one query - sql

So i designed a 'CD shop Database' and tried to write one query for all of it's elements but for some reason i can't create and add tables to that Database in one query. Here is my query :
CREATE DATABASE CDCI
ON PRIMARY(
Name = cddukkan_data,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.mdf',
Size = 16 MB,
FileGrowth = 1 MB,
MaxSize = 1 GB
)
LOG ON(
Name = cddukkan_log,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.ldf',
Size = 8 MB,
FileGrowth = 5%,
MaxSize = 512 MB
)
USE CDCI >An error occurs here
GO
CREATE TABLE Turler(
TurID INT IDENTITY(1, 1) NOT NULL,
TurAdi NVARCHAR(10) NOT NULL,
PRIMARY KEY(TurID),
UNIQUE(TurID)
)
CREATE TABLE Yonetmenler(
YonetmenID INT IDENTITY(1, 1) NOT NULL,
YonetmenAdi NVARCHAR(10) NOT NULL,
YonetmenSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19__' OR (DogumYili LIKE '20__' AND DogumYili < (YEAR(GETDATE()) - 18))),
Cinsiyet NCHAR(5),
CONSTRAINT Cinsiyet CHECK(Cinsiyet LIKE '[Ee]%' OR Cinsiyet LIKE '[Kk]%'),
PRIMARY KEY(YonetmenID),
UNIQUE(YonetmenID)
)
CREATE TABLE Raflar(
RafID INT IDENTITY(1, 1) NOT NULL,
RafTuru INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
PRIMARY KEY(RafID),
UNIQUE(RafID)
)
CREATE TABLE Filmler(
FilmID INT IDENTITY(1, 1) NOT NULL,
FilmAdi NVARCHAR(10) NOT NULL,
TurID INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
YonetmenID INT FOREIGN KEY REFERENCES Yonetmenler(YonetmenID) NOT NULL,
RafID INT FOREIGN KEY REFERENCES Raflar(RafID) NOT NULL,
Fiyat MONEY NOT NULL,
PRIMARY KEY(FilmID),
UNIQUE(FilmID)
)
CREATE TABLE Musteriler(
MusteriID INT IDENTITY(1, 1) NOT NULL,
MusteriAdi NVARCHAR(10) NOT NULL,
MusteriSoyadi NVARCHAR(10) NOT NULL,
Adresi NVARCHAR(20),
Telefon NVARCHAR(10),
CONSTRAINT Telefon CHECK(Telefon NOT LIKE '0%'),
PRIMARY KEY(MusteriID)
)
CREATE TABLE Oyuncular(
OyuncuID INT IDENTITY(1, 1) NOT NULL,
OyuncuAdi NVARCHAR(10) NOT NULL,
OyuncuSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19%' OR DogumYili < YEAR(GETDATE())),
PRIMARY KEY(OyuncuID),
UNIQUE(OyuncuID)
)
CREATE TABLE Satislar(
SatisID INT IDENTITY(1, 1) NOT NULL,
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
MusteriID INT FOREIGN KEY REFERENCES Musteriler(MusteriID) NOT NULL,
SatisAdedi INT NOT NULL
)
CREATE TABLE FilmOyuncu(
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
OyuncuID INT FOREIGN KEY REFERENCES Oyuncular(OyuncuID) NOT NULL
)
USE CDCI >An error occurs here
GO
CREATE TRIGGER [TelefonKontrol]
ON [Musteriler]
FOR INSERT
AS
DECLARE #tel NVARCHAR(10)
SELECT #tel = Telefon FROM INSERTED
IF #tel LIKE '0%'
BEGIN
PRINT 'Lütfen telefon numarasýný baþýna 0 rakamý koymayýnýz.'
ROLLBACK TRAN
END
GO
CREATE TRIGGER [FilmRafTuruUyumu]
ON [Filmler]
FOR INSERT
AS
DECLARE #filmTuru NVARCHAR(10)
DECLARE #rafTuru NVARCHAR(10)
DECLARE #rafID NVARCHAR(10)
SELECT #rafID = RafID FROM INSERTED
SELECT #filmTuru = TurID FROM INSERTED
SELECT #rafTuru = Raflar.RafTuru FROM INSERTED
INNER JOIN Raflar ON Raflar.RafID = #rafID
IF #rafTuru <> #filmTuru
BEGIN
PRINT 'Lütfen film uygun rafa yerleþtiriniz!'
ROLLBACK TRAN
END
GO
NOTE : I'm not new to the Database stuff because i got some classes of it but those were very basic level and theory-based classes. So you can consider me as 'starter'. Any helps, tips and suggestions are appriciated!

You need to check your location path for mdf and ldf files.
CREATE DATABASE CDCI
ON PRIMARY(
Name = cddukkan_data,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.mdf',
Size = 16 MB,
FileGrowth = 1 MB,
MaxSize = 1 GB
)
LOG ON(
Name = cddukkan_log,
FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL14.VERITABANIM\MSSQL\DATA\cdci.ldf',
Size = 8 MB,
FileGrowth = 5%,
MaxSize = 512 MB
)
go
USE CDCI -->An error occurs here
GO
CREATE TABLE Turler(
TurID INT IDENTITY(1, 1) NOT NULL,
TurAdi NVARCHAR(10) NOT NULL,
PRIMARY KEY(TurID),
UNIQUE(TurID)
)
CREATE TABLE Yonetmenler(
YonetmenID INT IDENTITY(1, 1) NOT NULL,
YonetmenAdi NVARCHAR(10) NOT NULL,
YonetmenSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19__' OR (DogumYili LIKE '20__' AND DogumYili < (YEAR(GETDATE()) - 18))),
Cinsiyet NCHAR(5),
CONSTRAINT Cinsiyet CHECK(Cinsiyet LIKE '[Ee]%' OR Cinsiyet LIKE '[Kk]%'),
PRIMARY KEY(YonetmenID),
UNIQUE(YonetmenID)
)
CREATE TABLE Raflar(
RafID INT IDENTITY(1, 1) NOT NULL,
RafTuru INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
PRIMARY KEY(RafID),
UNIQUE(RafID)
)
CREATE TABLE Filmler(
FilmID INT IDENTITY(1, 1) NOT NULL,
FilmAdi NVARCHAR(10) NOT NULL,
TurID INT FOREIGN KEY REFERENCES Turler(TurID) NOT NULL,
YonetmenID INT FOREIGN KEY REFERENCES Yonetmenler(YonetmenID) NOT NULL,
RafID INT FOREIGN KEY REFERENCES Raflar(RafID) NOT NULL,
Fiyat MONEY NOT NULL,
PRIMARY KEY(FilmID),
UNIQUE(FilmID)
)
CREATE TABLE Musteriler(
MusteriID INT IDENTITY(1, 1) NOT NULL,
MusteriAdi NVARCHAR(10) NOT NULL,
MusteriSoyadi NVARCHAR(10) NOT NULL,
Adresi NVARCHAR(20),
Telefon NVARCHAR(10),
CONSTRAINT Telefon CHECK(Telefon NOT LIKE '0%'),
PRIMARY KEY(MusteriID)
)
CREATE TABLE Oyuncular(
OyuncuID INT IDENTITY(1, 1) NOT NULL,
OyuncuAdi NVARCHAR(10) NOT NULL,
OyuncuSoyadi NVARCHAR(10) NULL,
DogumYili NCHAR(4),
CONSTRAINT DogumYili CHECK(DogumYili LIKE '19%' OR DogumYili < YEAR(GETDATE())),
PRIMARY KEY(OyuncuID),
UNIQUE(OyuncuID)
)
CREATE TABLE Satislar(
SatisID INT IDENTITY(1, 1) NOT NULL,
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
MusteriID INT FOREIGN KEY REFERENCES Musteriler(MusteriID) NOT NULL,
SatisAdedi INT NOT NULL
)
CREATE TABLE FilmOyuncu(
FilmID INT FOREIGN KEY REFERENCES Filmler(FilmID) NOT NULL,
OyuncuID INT FOREIGN KEY REFERENCES Oyuncular(OyuncuID) NOT NULL
)
USE CDCI -->An error occurs here
GO
CREATE TRIGGER [TelefonKontrol]
ON [Musteriler]
FOR INSERT
AS
DECLARE #tel NVARCHAR(10)
SELECT #tel = Telefon FROM INSERTED
IF #tel LIKE '0%'
BEGIN
PRINT 'Lütfen telefon numarasýný baþýna 0 rakamý koymayýnýz.'
ROLLBACK TRAN
END
GO
CREATE TRIGGER [FilmRafTuruUyumu]
ON [Filmler]
FOR INSERT
AS
DECLARE #filmTuru NVARCHAR(10)
DECLARE #rafTuru NVARCHAR(10)
DECLARE #rafID NVARCHAR(10)
SELECT #rafID = RafID FROM INSERTED
SELECT #filmTuru = TurID FROM INSERTED
SELECT #rafTuru = Raflar.RafTuru FROM INSERTED
INNER JOIN Raflar ON Raflar.RafID = #rafID
IF #rafTuru <> #filmTuru
BEGIN
PRINT 'Lütfen film uygun rafa yerleþtiriniz!'
ROLLBACK TRAN
END
GO

Related

there is already an object named '' in the database

This is my code:
CREATE TABLE supplier -- creating table supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO
I get the the error:
Msg 2714, Level 16, State 6, Line 34
There is already an object named 'supplier' in the database.
Any help? Thanks!
Please try this code.
IF EXISTS(SELECT 1 FROM sys.tables WHERE name = 'supplier')
DROP TABLE dbo.supplier;
CREATE TABLE dbo.supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO
You need to check if the table exists first
IF OBJECT_ID('dbo.supplier', 'U') IS NOT NULL
DROP TABLE dbo.supplier;
CREATE TABLE dbo.supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO
If you are using 2016+ you can use
DROP TABLE IF EXISTS dbo.supplier;
CREATE TABLE dbo.supplier
(
supplierID INT NOT NULL IDENTITY,
supplierName VARCHAR(30) NOT NULL,
suppplierNo VARCHAR(10) NOT NULL,
supplierEmail VARCHAR(30) NOT NULL,
CONSTRAINT PK_supplierID PRIMARY KEY(supplierID)
)
GO

Relationship 1 to n

create database shop1
use shop1
create table mathang
(
MatHangID INT primary key not null,
TenMatHang varchar(50),
SoLuong int not null,
Price int not null,
)
create table nhacungcap
(
MatHangID INT foreign key references mathang,
TenNhaCungCap varchar(50) ,
DiaChi varchar(100),
SoDienThoai int ,
CONSTRAINT pk_M_CC primary key (MatHangID)
)
create table khachhang
(
KhachHangID int not null primary key,
TenKhachHang varchar(50) not null,
[DiaChi] varchar(100) not null,
[SoDienThoai] varchar(50) not null,
)
create table donhang
(
DonHangID int references to khachhang(KhachHangID),
TenDonHang varchar(50),
SoLuong int,
CONSTRAINT pk_DHID primary key (DonHangID)
)
I can not find errors with this, it shows the foreign key error to add this relation ship. Any one please help.
Remove the to in
...
DonHangID int references to khachhang(KhachHangID)
...
to get
...
DonHangID int references khachhang(KhachHangID)
...
. The to doesn't belong there syntactically.

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)

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.

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.