SQL FOREIGN KEY constraint in Insert - sql-server

I've got a problem to insert some values into table.
Microsoft SQL server management shows that:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Players__Menager__55D59338". The conflict occurred in database
"TransferyProjekt", table "dbo.Menagers", column 'idMenager'.
My Create table script.
CREATE TABLE Menagers (
idMenager INT IDENTITY(1,1) NOT NULL,
[name] VARCHAR(30) NOT NULL CHECK (name LIKE '[A-Z]%'),
surname VARCHAR(30) NOT NULL CHECK (surname LIKE '[A-Z]%'),
phoneNumber VARCHAR(18) NOT NULL CHECK (phoneNumber LIKE '+[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'),
PRIMARY KEY (idMenager)
);
CREATE TABLE Players (
idPlayer INT IDENTITY(1,1) NOT NULL,
[name] VARCHAR(30) NOT NULL,
surname VARCHAR(30) NOT NULL,
age DATE NOT NULL check (DATEDIFF(year,age,GETDATE()) > 18),
club INT NOT NULL,
Menager INT NOT NULL,
PRIMARY KEY (idPlayer),
FOREIGN KEY (club) REFERENCES Clubs(idClub),
FOREIGN KEY (Menager) REFERENCES Menagers(idMenager)
);
My insert look like.
INSERT INTO Menagers VALUES
('Adil','Green','+232247832'),
('Wicky','Dock','+301494064'),
('Alead','King','+447499384'),
('Darmian','Dagoly','+445587849'),
('Kamila','Dobra','+958789278'),
('Mateusz','Jankowiak','+849383098'),
('Lendy','Day','+448902920'),
('Martin','Lloyd','+501044468'),
('Adam','Dosh','+045033739'),
('Cristian','Cosy','+307748735'),
('Andrew','Lloyd','+635875452'),
('Matias','Banega','+520091224'),
('Carl','Rossi','+196935415'),
('Michał','Rolnik','+156541588'),
('Denny','Nowsky','+231785387'),
('Micky','Elly','+125774609'),
('George','Taylor','+094371433'),
('Barack','Obama','+916764868'),
('Jin','Chan','+906765545'),
('Lee','Konsu','+608935829'),
('Adam','Kenzo','+417708081'),
('Bryan','Along','+939454178'),
('Robert','Leey','+183354912'),
('Tom','Vardy','+576176145'),
('Kevin','Betword','+721582207');
INSERT INTO Players VALUES
('Lionel','Messi','1986-07-13','23','4'),
('Cristiano','Ronaldo','1986-04-11','23','5'),
('Sergio','Ramos','1986-09-07','23','12'),
('Łukasz','Piszczek','1986-11-20','23','14'),
('Robert','Lewandowski','1986-12-01','2','13'),
('Michał','Pazdan','1986-06-01','3','23'),
('Łukasz','Trałka','1986-05-02','7','20'),
('Łukasz','Teodorczyk','1986-04-14','6','18'),
('Mariusz','Miley','1985-03-06','3','26');

You should define column names if your source table and destination table has different column counts or different order
INSERT INTO Menagers([name],surname, phoneNumber )
VALUES
('Adil','Green','+232247832'),
('Wicky','Dock','+301494064'),
....
INSERT INTO Players([name], surname, age, club, Menager )
VALUES
('Lionel','Messi','1986-07-13','23','4'),
('Cristiano','Ronaldo','1986-04-11','23','5'),
...

Your foreign key and primary key columns are INT type. But, you are having following SQL
INSERT INTO Players VALUES
('Lionel','Messi','1986-07-13','23','4')
where last column belongs to foreign key column and your value is string.

A foreign key is a reference to a unique value in a different table, and SQL will ensure "referential integrity" - which means it won't let you end you with "orphaned" key references. When you insert a value to a foreign key column it must be a null or a existing reference to a row in the other table, and when you delete, you must delete the row containing the foreign key first, then the row it references.
If you don't, you will get an error such as you describe.
So enter the row into the "main" table first, then enter the "dependant" table information second.

In FK column I added unfortunately referece to row who is not exists in table Managers...
('Mariusz','Miley','1985-03-06','3','26');
but I don't have 26'th row in table Managers (Blame me, now) :(

Related

Unable to add a constraint foreign key to a table from an already created table in SQL server management studio 18. Can someone help me?

I'm creating a database for my assignment. I had to create 2 tables namely Customer and Job through the "New Query" option in SQL server. After creating both of them, I wanted to add Job_ID (A primary key) from Job table as a foreign key to the Customer table. As I have already created the Customer table, The only option I had was to ALTER the customer table. But after altering, I seemed to get this unusual error.
Msg 1769, Level 16, State 1, Line 1
Foreign key 'Job_ID' references invalid column 'Job_ID' in referencing table 'CUSTOMER'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint or index. See previous errors.
I can provide you with any more info if necessary.
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
CREATE TABLE JOB
(Job_ID INT NOT NULL PRIMARY KEY,
Pickup_location VARCHAR (10) NOT NULL,
Destination VARCHAR (10) NOT NULL,
Customer_ID INT FOREIGN KEY REFERENCES CUSTOMER(Customer_ID));
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
This looks like the same issue as described here.
When you try to create your foreign key:
ALTER TABLE CUSTOMER
ADD FOREIGN KEY (Job_ID) REFERENCES JOB(Job_ID);
You are saying that you want to use the field Job_ID from the table CUSTOMER:
ALTER TABLE CUSTOMER ADD FOREIGN KEY (Job_ID)
and that the values in this field should match values in the Job_ID column from the table JOB:
REFERENCES JOB(Job_ID);
The problem is that your CUSTOMER table doesn't have a Job_ID column, based on its definition:
CREATE TABLE CUSTOMER
(Customer_ID INT NOT NULL PRIMARY KEY,
Customer_Name VARCHAR(15) NOT NULL,
Gender CHAR(1),
Customer_Type VARCHAR(12) NOT NULL,
Addresss VARCHAR(20) NOT NULL,
Telephone_No CHAR(10) NOT NULL);
The fields in the CUSTOMER table are Customer_ID,Customer_Name,Gender,Customer_Type,Addresss and Telephone_No.
So you either need to add a Job_ID column to the CUSTOMER table, or specify a different field to use in your ALTER TABLE statement - one which does exist in the CUSTOMER table.
More information on ALTER TABLE and ADD FOREIGN KEY specifically can be found here.

Foreign key references invalid table. Could not create constraint or index

I'm trying to create a table with 3 columns. The first column should be an identity column named DescriptionsID, the second column should be a foreign key column named ProductID, and the third column should be an xml column named Description. But, I'm receiving an error:
Foreign Key 'FK_ProductDescriptions_bacb18ce3aa67348e55d' references invalid table 'Product' and "Could not create constraint or index. See previous errors."
This is what I got:
CREATE TABLE ProductDescriptions (DescriptionsID int PRIMARY KEY NOT NULL,
ProductID varchar(25) NOT NULL,
FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
Description text NULL) ;
References Product(ProductID) has the error/red underlining
When you create a Referential Constraint, You Need to make sure that the Table and the Column which you are referring already exists in the Database.
Also, the Datatype of Both Referring Column and the Referred Column Should Be the Same
Column 'Product.ProductId' is not the same data type as referencing column
'ProductDescriptions.ProductID' in the foreign key
So Create Product Table First, and set the Product Id as Primary Key
CREATE TABLE Product
(
ProductId INT IDENTITY(1,1) PRIMARY KEY,
ProductName VARCHAR(50)
)
CREATE TABLE ProductDescriptions
(
DescriptionsID int PRIMARY KEY NOT NULL,
ProductID INT NOT NULL
,FOREIGN KEY (ProductID) REFERENCES Product(ProductID),
[Description] text NULL
) ;

set the column code as foreign key on table with a reference to another table

enter image description hereI got a problem regarding my two table. The name of one table tblShoes and the other one is tblplayer. the problem is I want to Set the column Code in table tblPLAYERS as FOREIGN KEY with a reference to table tblSHOES column code. but I trying to insert my code in table tblPLAYER but it doesn't work can you help me and explain why please.
here is my two table.
create table tbl_Shoe
(
code varchar not null primary key,
brand varchar not null,
model int not null,
size varchar not null
);
create table tbl_PLAYER
(
RosterNo int primary key,
Name varchar ,
Position varchar,
Code varchar
primary key (code),
foreign key (Code) references tblShoe (code)
);
help me please! you are very big help for me. thanks a lot.
this is my code
http.clickimage
When you define a foreign key, you're saying "hey database, guarantee that this value exists in the other table". In your case, you're saying that for whatever value you're putting in the tblPlayer.Code column, there needs to be a matching row that has the same value in tblShoe. For example, if I only have codes A, B, and C in tblShoe and I try to insert a row into tblPlayer with a code of D, it won't work.
A foreign key is a reference to another table. It is used to establish relationships between tables. For example, relationship between tbl_Shoe and tbl_PLAYER table. One tbl_Shoe can have multiple codes. The Primary key of tbl_Shoe becomes foreign key of codes of another table which is the tbl_PLAYER.so here is my answer.
create table tbl_Shoes
Codes varchar (20) not null primary key,
brand varchar(50) not null,
model int not null,
size varchar(10) not null
);
create table tbl_PLAYERS
(
RosterNo int primary key,
Name varchar(20) ,
Position varchar(20),
code varchar (20) not null,
Codes varchar (20) not null constraint fk_code foreign key references tblShoes(Codes)
);

SQL Server - Adding foreign key to a table

As in my previous post (linked here) I have been designing a table and I'm trying to insert only some specific values into the BrothersName column which can be done by adding a constraint.
TABLE Family
(
BrothersName varchar(30)
);
However my question now is that I'm trying to do this instead by foreign key. Is the only way to do it is by making a new table and add primary key into it?
What can be the best way otherwise?
So you should have a primary key table to hold all possible master data set for brother names like below
create table MasterBrotherNames (ID int IDENTITY(1,1) PRIMARY KEY, Name nvarchar(30)) ;
insert into MasterBrotherNames(Name) values (N'Alex'),(N'Tom');
Now you should hold foreign key ID into the Family table as int, say in column BrothersNameID using following query to create FK relationship
create table Family( BrothersNameID int NOT NULL);
alter table Family add constraint fk_family_brothername foreign key ( BrothersNameID ) references MasterBrotherNames (ID);
To test out try queries below
insert into Family values (1)-- for Alex
insert into Family values (2)-- for Tom
insert into Family values (3)-- this gives error
--The INSERT statement conflicted with the FOREIGN KEY constraint "fk_family_brothername".
Based on OP's following request
is there any way to implement this without having any Id in MasterBrothersName, where only names can be inserted and accepted as values
here's the modified query
create table MasterBrotherNames ( Name nvarchar(30) PRIMARY KEY) ;
insert into MasterBrotherNames(Name) values (N'Alex'),(N'Tom');
create table Family( BrothersName nvarchar(30) NOT NULL);
alter table Family add constraint fk_family_brothername foreign key ( BrothersName ) references MasterBrotherNames (Name);
insert into Family values (N'Alex')-- for Alex
insert into Family values (N'Tom')-- for Tom
insert into Family values (N'A')-- this gives error
--The INSERT statement conflicted with the FOREIGN KEY constraint "fk_family_brothername".

Error upon creating tables in sqlplus

I'm new to sqlplus and was trying to run a sql script that creates a few tables, but once I try to run it, it gives me an error saying that the table or view doesnt exist and I dont know how to fix this error.
My script is:
drop table Borrower;
create table Borrower (
bid char(100) not null,
password char(100) not null,
name char(100) null,
address char(100) null,
phone char(100) null,
emailAddress char(100) null,
sinOrStNo char(100) null,
expiryDate date null,
--type ENUM('student','faculty','staff'),
type char(100) not null,
--CONSTRAINT Btype_check CHECK (type IN ('student','faculty','staff')),
FOREIGN KEY (type) references BorrowerType(type),
PRIMARY KEY (bid));
grant select on Borrower to public;
"unique/primary keys in table referenced by foreign keys "
Data integrity is crucial to a properly run database so Oracle will not let us drop a table if its primary key is referenced by another table's foreign key. So it hurls ORA-02449.
So, given this set up:
create table t_parent (
id number not null
, constraint tp_pk primary key (id)
);
create table t_child (
id number not null
, p_id number not null
, constraint tc_pk primary key (id)
, constraint tc_tp_fk foreign key (p_id)
references t_parent (id)
);
There are three ways to drop table t_parent.
run drop table t_child first: no child table, no foreign key.
Remove the blocking foreign key: alter table t_child drop constraint tc_pc_fk.
A variant on the previous one, let the database figure out the foreign keys:
drop table t_parent cascade constraints.
The first option is the most proper, because it leaves the database in a valid state (no tables, no possibility of data integrity corruption). The valid use for the third approach is a script which razes all the tables from a schema: it's easy to generate such a script from the data dictionary.
The order that you drop or create tables are important because if you have foreign keys referencing another table, you cant delete that table before deleting your own table.
In this example, the Borrower table has to be dropped before the BorrowerType table.

Resources