Error Create Foreign Key SQL - sql

CREATE TABLE Usuario
(
id int identity not null,
usuario char(20) unique not null,
senha char(10) not null,
tipo_usuario char(15) not null,
primary key (id),
foreign key (tipo_usuario) references TpoUsuario
on update cascade on delete set default
);
CREATE TABLE TpoUsuario
(
id int identity not null,
tipo_usuario char(15) not null,
primary key(id)
);
This use a codes to top, and received this message error.
First I created table TpoUsuario, then I created table Usuario.
Msg 1778, Level 16, State 0, Line 1
Column 'TpoUsuario.id' is not the same data type as referencing column 'Usuario.tipo_usuario' in foreign key 'FK__Usuario__tipo_us__60A75C0F'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

TpoUsuario.id is an int data type column while Usuario.tipo_usuario is char type column
Could you link Usuario.id with TpoUsuario.id or Usuario.usario with TpoUsuario.tipo_usuario

See how to define foreign-keys:
SQL FOREIGN KEY
You say
foreign key (tipo_usuario) references TpoUsuario on update cascade on delete set default
Syntax is FOREIGN KEY (column col1, column col2, ...) REFERENCES table_name(column col1, column col2,...)

Related

SQL queries - There are no primary or candidate > keys in the referenced table

I am trying to create some tables in SQL but when I am running these queries, I am getting the following exception:
Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'Couple' that match the referencing column list in the foreign key 'FK__wedding__CoupleN__2739D489'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
CREATE TABLE Person
(
FirstName nvarchar (25) NOT NULL,
SurName nvarchar (25) NOT NULL,
id char(9) PRIMARY KEY
CHECK (id LIKE REPLICATE('[0-9]',9)),
PhoneNumber char(10)
CHECK (PhoneNumber LIKE REPLICATE('[0-9]',10)),
Birthday date
CHECK ((GETDATE() - YEAR(Birthday)) > 10)
);
CREATE TABLE Couple
(
Number int identity(1000,1),
Partner1 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
Partner2 char(9)
REFERENCES Person(Id) ON DELETE NO ACTION,
CoupleName varchar(25) NOT NULL,
CONSTRAINT PK_Couple1 CHECK (Partner1 <> Partner2),
CONSTRAINT PK_Couple PRIMARY KEY (Partner1, Partner2, Number)
);
CREATE TABLE weddinghall
(
Name varchar (25) PRIMARY KEY,
SeveralSeats int
CHECK (SeveralSeats >= 50 AND SeveralSeats <= 5000),
Kosher char(1)
CHECK (works = 'Y' OR not = 'N'),
PlaceType varchar(25)
CHECK (PlaceType IN s, 'b', 'd', 'doif')),
NumberOfParkingSpaces int
);
CREATE TABLE wedding
(
WeddingHallName varchar (25)
REFERENCES weddinghall(Name) ON DELETE CASCADE,
CoupleNumber int
REFERENCES Couple (Number) ON DELETE CASCADE,
WeddingDate date,
NumberOfGuests Int ,
CONSTRAINT PK_Wedding PRIMARY KEY (CoupleNumber, WeddingHallName)
);
CREATE TABLE WeddingGuests
(
GuestId char(9) references Person (Id) ON DELETE cascade,
CoupleNumber int references Couple (Number) ON DELETE cascade,
WeddingDate date,
WeddingHallName varchar (25) references weddinghall(Name) ON DELETE cascade,
ArrivalConfirmation CHAR(1),
ArrivingToWedding Char(1),
CONSTRAINT PK_WeddingGuests
PRIMARY KEY (GuestId, CoupleNumber, WeddingDate, WeddingHallName)
);
Can you please help?
The error message is telling you that you don't have a unique constraint or primary key on dbo.Couple.Number. That is the third key column in your primary key constraint, and you can't point a foreign key there. You can either:
Add a unique constraint on dbo.Couple.Number
Change the PK to a unique constraint and make dbo.Couple.Number the single-column primary key.

How can I have two foreign keys in a table?(SQL-Server)

I have the following tables.
CREATE TABLE USERINFO(
USERID CHAR(20) NOT NULL,
PW CHAR(20),
POINT INT DEFAULT 5000,
PRIMARY KEY(USERID)
);
CREATE TABLE MESSAGE(
NO INT NOT NULL IDENTITY(1,1),
WRITER CHAR(20) DEFAULT NULL,
RECEIVER CHAR(20) DEFAULT NULL,
CONTENT CHAR(100),
PRIMARY KEY(NO),
FOREIGN KEY(WRITER) REFERENCES USERINFO(USERID) ON DELETE SET NULL,
FOREIGN KEY(RECEIVER) REFERENCES USERINFO(USERID) ON DELETE SET NULL
);
This is error code.
Msg 1785, Level 16, State 0, Line 125 Introducing FOREIGN KEY
constraint 'FK__MESSAGE__RECEIVE__379B24DB' on table 'MESSAGE' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Msg 1750, Level 16, State 1, Line 125 Could not create constraint or
index. See previous errors.
I know I'm completely wrong, but I don't know how to fix it.

No primary or candidate key in the referenced table

I have created a table Request which has a primary key made up from three columns, and also a foreign key
CREATE TABLE Request
(
Iqama varchar(255) ,
Cid int,
ReqID int,
FOREIGN KEY (Iqama, Cid) REFERENCES Users(Iqama, ID),
PRIMARY KEY (Cid, Iqama, ReqID)
);
I also created the table below which is a multi-valued attribute for table Request, however I am getting an error
Msg 1776, Level 16, State 0, Line 51
There are no primary or candidate keys in the referenced table 'Request' that match the referencing column list in the foreign key 'FK__Request_Services__151B244E'.
Msg 1750, Level 16, State 1, Line 51
Could not create constraint or index. See previous errors.
The table:
CREATE TABLE Request_Services_chosen
(
Iqama varchar(255) ,
Cid int,
ReqId_ int,
Servicechosen varchar(255),
FOREIGN KEY (ReqId_, Iqama, Cid) REFERENCES Request(ReqID, Iqama, Cid),
PRIMARY KEY (ReqId_, Iqama, Cid, Servicechosen)
);
and here is the Users table:
CREATE TABLE Users
(
ID int NOT NULL,
Iqama varchar(255) NOT NULL,
Name varchar(255),
Password varchar(255),
Phone varchar(255),
PRIMARY KEY (Iqama, ID)
);
The primary key in request is defined as (cid, iqama, reqid) but in your REFERENCES clause in request_services_chosen you use (reqid, iqama, cid). That's the wrong order.
Use the same order.
CREATE TABLE Request_Services_chosen(
...
FOREIGN KEY (Cid,Iqama,ReqId_) REFERENCES Request(Cid,Iqama,ReqID),
...
);

SQL Server - Referencing another column in a CHECK clause

hope you're having a good day.
I want to do something like this.
CREATE TABLE Certificat
(
num_certificat SMALLINT NOT NULL,
description TEXT NOT NULL,
Date_depot DATE NOT NULL CHECK(Date_depot <= GETDATE()),
Date_validation DATE NOT NULL CHECK(Date_validation > Date_depot),
num_auteur SMALLINT NOT NULL,
num_innovation SMALLINT NOT NULL,
CONSTRAINT pk_numc PRIMARY KEY(num_certificat),
CONSTRAINT fk_au FOREIGN KEY(num_auteur) REFERENCES Auteur(num_auteur) ON
DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_inn FOREIGN KEY(num_innovation) REFERENCES
Innovation(num_innovation) ON DELETE CASCADE ON UPDATE CASCADE,
);
But I get this error:
Msg 8141, Level 16, State 0, Line 4
Column CHECK constraint for column 'Date_validation' references another column, table 'Certificat'.
Msg 1750, Level 16, State 0, Line 4
Could not create constraint or index. See previous errors.
So how can I reference another column into a CHECK clause? I want the table to reject entries with the Date_depot greater than Date_validation.
You need to create it at the table level - not inline next to a column.
CREATE TABLE Certificat
(
num_certificat SMALLINT NOT NULL,
description TEXT NOT NULL,
Date_depot DATE NOT NULL CHECK(Date_depot <= GETDATE()),
Date_validation DATE NOT NULL,
num_auteur SMALLINT NOT NULL,
num_innovation SMALLINT NOT NULL,
CHECK(Date_validation > Date_depot), /*<----- Moved here*/
CONSTRAINT pk_numc PRIMARY KEY(num_certificat),
CONSTRAINT fk_au FOREIGN KEY(num_auteur) REFERENCES Auteur(num_auteur) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_inn FOREIGN KEY(num_innovation) REFERENCES Innovation(num_innovation) ON DELETE CASCADE ON UPDATE CASCADE,
);
You should also consider giving it an explicit name. For example
CONSTRAINT ck_validation_after_depot CHECK(Date_validation > Date_depot)

I'm trying to alter one of my tables and adding a foreign key it I keep getting the same error

The error I get is:
Msg 1769, Level 16, State 1, Line 30
Foreign key 'fk_pid' references invalid column 'P_ID' in referencing table 'Detainee'.
My table structure:
create table Detainee
(
D_ID bigint primary key identity not null,
Fname nvarchar(50),
Lname nvarchar(50),
Address varchar(200),
DateOfBirth date,
DateOfArrest date,
SourceOfArrest nvarchar(max)
);
create table PrisonCell
(
P_ID bigint primary key not null,
Capacity int,
RemCap int,
C_Type varchar(20)
);
Code to alter table:
alter table Detainee
add constraint fk_pid foreign key(P_ID) references PrisonCell(P_ID)
What you need to do is:
add the column P_ID BIGINT to your table Detainee
then add the FK constraint to that column
Just adding the FK constraint to the table isn't going to automagically add a column as well...
You should be able to do this in a single step:
ALTER TABLE Detainee
ADD P_ID BIGINT
CONSTRAINT fk_pid FOREIGN KEY REFERENCES PrisonCell(P_ID);