Please help to understand "Foreign key constraint is incorrectly formed" issue in this code
create TABLE books
(
book_id INT NOT NULL AUTO_INCREMENT,
book_name VARCHAR(255) NOT NULL,
book_description VARCHAR(255) NOT NULL,
book_number_of_pages INT NOT NULL,
book_state VARCHAR(255) NOT NULL,
author_name VARCHAR(255) NOT NULL,
PRIMARY KEY (book_id)
);
create TABLE authors
(
author_id INT NOT NULL AUTO_INCREMENT,
author_name VARCHAR(255) NOT NULL,
author_surname VARCHAR(255) NOT NULL,
book_name VARCHAR(255) NOT NULL,
PRIMARY KEY (author_id),
FOREIGN KEY (book_name) REFERENCES books (book_name)
ON DELETE CASCADE
ON UPDATE CASCADE
);
The 2nd create table statement failed, since the referenced column book_name in table books has no index.
create TABLE books (
book_id INT NOT NULL AUTO_INCREMENT,
book_name VARCHAR(255) NOT NULL,
book_description VARCHAR(255) NOT NULL,
book_number_of_pages INT NOT NULL,
book_state VARCHAR(255) NOT NULL,
author_name VARCHAR(255) NOT NULL,
PRIMARY KEY (book_id),
KEY(book_name)
);
However it's not a good design to store information (book_name) redundant. Instead of book_name you should store the id.
Related
I'm trying to develop an app for a driving school.
I have a table for instructors:
CREATE TABLE [dbo].[Instructori]
(
[nume] NVARCHAR(50) NOT NULL,
[prenume] NVARCHAR(50) NOT NULL,
[CNP] CHAR(13) NOT NULL,
[Nastere] SMALLDATETIME NOT NULL,
[Angajare] SMALLDATETIME NOT NULL,
[IDmasina] INT NOT NULL,
[IDCategorie] INT NOT NULL,
[Sex] NCHAR(1) NOT NULL,
[NrStudenti] INT NULL DEFAULT 0,
[RataPromovare] DECIMAL(5, 2) NULL DEFAULT 0,
[TotalStudenti] AS [dbo].Total_Stud(CNP),
CONSTRAINT [PK_Instructori] PRIMARY KEY CLUSTERED ([CNP] ASC),
CONSTRAINT [Instr]
FOREIGN KEY ([IDCategorie]) REFERENCES [dbo].[Categorie] ([IDCategorie]),
);
One for Students:
CREATE TABLE [dbo].[Studenti]
(
[nume] NVARCHAR(50) NOT NULL,
[prenume] NVARCHAR(50) NOT NULL,
[Nastere] SMALLDATETIME NOT NULL,
[Legislatie_p] INT NULL,
[Categorii_dobandite] NVARCHAR(50) NULL,
[Categorie] INT NOT NULL,
[Data_examnen] SMALLDATETIME NOT NULL,
[IDLectie] INT NOT NULL,
[CNP] CHAR(13) NOT NULL,
[CNPI] CHAR(13) NOT NULL,
CONSTRAINT [PK_Studenti] PRIMARY KEY CLUSTERED ([CNP] ASC),
CONSTRAINT [FK_Categorie]
FOREIGN KEY ([Categorie]) REFERENCES [dbo].[Categorie] ([IDCategorie]),
CONSTRAINT [Lectie]
FOREIGN KEY ([IDLectie]) REFERENCES [dbo].[Legislatie] ([IDLectie]),
CONSTRAINT [Instructor1]
FOREIGN KEY ([CNPI]) REFERENCES [dbo].[Instructori] ([CNP])
);
and one for cars named "Masina" which is not really relevant.
"Conducere" is the linking table between the 3 others, and it's only used to count how many hours each student drive.
CREATE TABLE [dbo].[Conducere]
(
[CNP_Instructor] CHAR(13) NOT NULL,
[IDMasina] INT NOT NULL,
[CNP_Student] CHAR(13) NOT NULL,
[Numar_ore] INT NOT NULL DEFAULT 0,
PRIMARY KEY CLUSTERED ([CNP_Instructor] ASC),
CONSTRAINT [Student]
FOREIGN KEY ([CNP_Student]) REFERENCES [dbo].[Studenti] ([CNP]),
CONSTRAINT [FK_Masina]
FOREIGN KEY ([IDMasina]) REFERENCES [dbo].[Masina] ([IDMasina]),
CONSTRAINT [Instructor]
FOREIGN KEY ([CNP_Instructor]) REFERENCES [dbo].[Instructori] ([CNP])
);
I already coded a function for the total number of students for each instructor.
CREATE FUNCTION dbo.Total_Stud(#CNP CHAR(13))
RETURNS INT
AS
BEGIN
RETURN
(SELECT Count(CNP)
FROM Studenti
WHERE CNPI = #CNP)
END
I'm trying to find the students that have the same instructor(based on their CNP) and did not drive 30h yet. Students still in school ish.
You can SUM the hours for each student and filter the results by HAVING:
CREATE FUNCTION dbo.Student_Below_RequiredHours(#CNP CHAR(13),#RequiredHours int)
RETURNS TABLE
AS
BEGIN
RETURN
(SELECT CNP_Student
FROM [dbo].[Conducere]
WHERE CNP_Instructor = #CNP
GROUP BY CNP_Student
HAVING SUM([Numar_ore])<#RequiredHours)
END
I am getting an error
Incorrect syntax near ','
and do not know how to fix it.
I have tried rewriting the query, referencing old code, and nothing seems to work.
USE RewriteExam
GO
IF EXISTS(SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID('dbo.Vendors')
AND type IN ('U'))
BEGIN
PRINT 'Vendors table already exists, dropping it now!'
DROP TABLE Vendors
END
GO
PRINT 'Creating the "Vendors" Table'
CREATE TABLE dbo.Vendors
(
VendorID INT PRIMARY KEY,
VendorName VARCHAR(45) NOT NULL,
VendorAddress VARCHAR(45) NULL,
VendorCity VARCHAR(45) NOT NULL,
VendorState VARCHAR(45) NOT NULL,
VendorZipCode VARCHAR(45) NOT NULL,
VendorPhone VARCHAR(45) NULL,
VendorContactLName VARCHAR(7) NULL,
VendorContactFName VARCHAR(14) NULL,
AcountNo INT NOT NULL,
ModifiedDate SMALLDATETIME NOT NULL,
AccountNo INT FOREIGN KEY,
CONSTRAINT PK_Vendors_VendorID
PRIMARY KEY (VendorID)
--REFERENCES Vendors (VendorID)
);
GO
PRINT 'Creating the "GLAccounts" Table'
CREATE TABLE dbo.GLAccounts
(
AccountNo INT PRIMARY KEY,
AccountDescription VARCHAR(45) NOT NULL,
);
GO
The trouble is in the constraints. The comma after the foreign key is giving me the error as well as PRIMARY KEY (VendorID)
Just need to add the commented out part after
AccountNo INT FOREIGN KEY
and convert to
AccountNo INT FOREIGN KEY REFERENCES Vendors (VendorID)
and remove already defined constraint PRIMARY KEY (VendorID)
The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO
create table Vaixell (
Id_Vaixell varchar(20) not null,
Cabines numeric not null,
Restaurants numeric not null,
N_persones numeric not null,
PRIMARY KEY(Id_Vaixell)
);
create table Clients (
Id_client varchar(20) not null,
Id_billet varchar(20) not null,
DNI varchar(20) not null,
PRIMARY KEY(DNI,Id_billet,Id_client)
);
create table Cabina (
Id_cabina varchar(20) not null,
PRIMARY KEY (Id_cabina)
);
create table tipus_cabina (
Id_tipus varchar(20) not null,
Capacitat numeric not null,
PRIMARY KEY (Id_tipus)
);
create table Botigues (
Id_botiga varchar(20) not null,
Nom_botiga char(10) not null,
PRIMARY KEY(Id_botiga)
);
create table Tipus_botiga (
tipo_botiga varchar(20) not null,
PRIMARY KEY (tipo_botiga)
);
create table Rutes (
Id_epoca varchar(20) not null,
Id_ruta varchar(20) not null,
PRIMARY KEY (Id_ruta)
);
create table Treballadors (
DNI varchar(20) not null ,
Id_treballador varchar(20) not null,
Lloc_treball varchar(20) not null,
Dia date not null,
Hora TIMESTAMP not null,
Nom char(10) not null,
PRIMARY KEY(Id_treballador)
);
create table Restaurants(
Id_restaurant varchar(20) not null,
Id_menu varchar(20) not null,
Id_reserva varchar(20) not null,
Tipus varchar(20) not null,
Preu numeric not null,
PRIMARY KEY (Id_restaurant,Id_reserva,Id_menu)
);
create table Reserva (
Id_reserva varchar(20) not null,
Id_client varchar(20) not null,
Id_billet varchar(20) not null,
DNI varchar(20) not null,
Id_ruta varchar(20) not null,
Id_cabina varchar(20) not null,
Preus int not null,
Data_ date not null,
PRIMARY KEY (Id_reserva,Id_billet,Id_ruta,Id_cabina,DNI,Id_client),
CONSTRAINT clients_a_reserva_fk
FOREIGN KEY (Id_billet,DNI,Id_client)
references Clients (Id_billet,DNI,Id_client),
CONSTRAINT rutes_a_reserva_fk
FOREIGN KEY (Id_ruta)
references Rutes (Id_ruta),
CONSTRAINT cabina_a_reserva_fk
FOREIGN KEY (Id_cabina)
references Cabina (Id_cabina)
);
create table Excursions (
Edat_minima numeric not null,
Id_reserva varchar(20) not null,
Descripcio varchar(100) not null,
Opcional varchar(30) null,
PRIMARY KEY(Edat_minima,Id_reserva),
CONSTRAINT reserva_a_excursions_fk
FOREIGN KEY (Id_reserva)
references Reserva (Id_reserva)
);
create table Activitats (
tipus_activitat varchar(20) not null,
Id_reserva varchar(20) not null,
PRIMARY KEY (tipus_activitat,Id_reserva),
CONSTRAINT reserva_a_activitats_fk
FOREIGN KEY (Id_reserva)
references Reserva (Id_reserva)
);
create table Incidencies (
Id_treballador varchar(20) not null,
N_incidencia varchar(20) not null,
Dia date not null,
Hora TIMESTAMP not null,
Comentari varchar(100) null,
PRIMARY KEY(N_incidencia),
CONSTRAINT Incidencies_a_treballador_fk
FOREIGN KEY (Id_treballador)
references Treballadors (Id_treballador)
);
create table Port_desti (
N_port numeric(20) not null,
Id_ruta varchar(20) not null,
Ciutat_atracament varchar(20) not null,
PRIMARY KEY (N_port,Id_ruta),
CONSTRAINT ruta_a_port_fk
FOREIGN KEY (Id_ruta)
references Rutes (Id_ruta)
);
create table reserves_restaurant(
Id_reserva varchar(20) not null,
Id_menu varchar(20) not null,
PRIMARY KEY (Id_reserva,Id_menu),
CONSTRAINT Restaurants_a_reserves_fk
FOREIGN KEY (Id_reserva,Id_menu)
references Restaurants(Id_reserva,Id_menu)
);
create table client_a_reserva(
Id_client varchar(20) not null,
Id_restaurant varchar(20) not null,
PRIMARY KEY (Id_client, Id_restaurant),
CONSTRAINT clients_a_rerserva_fk
FOREIGN KEY (Id_client)
references Clients (Id_client),
CONSTRAINT Restaurant_a_clients_fk
FOREIGN KEY (Id_restaurant)
references Restaurants (Id_restaurant)
);
The columns in a foreign key must match the number and datatype of the columns in the referenced table's key.
You are expecting us to debug your several hundred lines of code which we are not going to do. What you need to do is stop running the whole script. One each statement individually. Then when one fails you know which one you need to fix.
`
I am new to SQL and I am trying to create a table with a constraint but I have not used the constrant before and I am not actually certain what this constraint does uc_ID on PId, LastName?
I want to create a constraint that will only allow alpha numeric values in a column?
Code:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT uc_ID UNIQUE (PId,LastName)
)
CREATE TABLE E
(
PId int identity(1,1) NOT NULL,
LastName varchar (25) NOT NULL,
FirstName varchar (25) NOT NULL,
Address1 varchar (25) NOT NULL,
City varchar (25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9]%')
)
Another Example (is not):
CREATE TABLE EEE
(
PId int identity(1,1) NOT NULL,
FirstName varchar (50) NOT NULL,
CONSTRAINT CHECK ([FirstName] LIKE '%[A-Za-z]%')
)
Means that the combination of Pid + LastName must be unique.
Since Pid is an identity, in normal circumstances it cannot be duplicated, so that constraint seems somehow redudant.
Try:
ALTER TABLE TableName ADD CONSTRAINT Only_Characters_And_Numbers CHECK ColumnName NOT LIKE '%[^A-Z0-9 ]%'
If you want a constraint that allows only alphanumeric characters in a column you can use this (for example for FirstName:
ALTER TABLE [Persons] ADD CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
Disclaimer: taken from here (and tested).
If you want the constraint to be added when the table is created:
CREATE TABLE Persons
(
PId int identity(1,1) NOT NULL,
LastName varchar(25) NOT NULL,
FirstName varchar(25) NOT NULL,
Address1 varchar(25) NOT NULL,
City varchar(25) NOT NULL
CONSTRAINT OnlyAlphanumeric CHECK ([FirstName] NOT LIKE '%[^A-Z0-9 ]%')
)
Note that constraint names are unique per database.
Alternatively, you can create an AFTER INSERT and AFTER UPDATE trigger to make this validation, but a constraint works just fine in this case.