Foreign key references invalid column error in MS SQL - sql

This is all in MS SQL.
I've seen this issue pop up a lot, and I searched around but I still can't figure out my issue. I'm getting the error telling me my foreign key references in invalid column in an uncreated table. However, I created the table as it shows up on my database table list, so it shows it is created.
I tried to move that said table above the table that references it, yet I'm still receiving the error. Would anyone know how to fix this?
My code:
CREATE SCHEMA usr_in;
go
CREATE TABLE gender_interst (
id int IDENTITY (1,1),
gend_id int
CONSTRAINT gender_interstpk PRIMARY KEY (id)
)
CREATE TABLE gender (
id int IDENTITY (1,1),
gend VARCHAR (20)
CONSTRAINT genderpk PRIMARY KEY (id)
);
SELECT * FROM gender_interst LEFT JOIN gender on gender_interst.id = gender.id;
SELECT * from gender_interst;
CREATE TABLE user_info (
id int PRIMARY KEY IDENTITY (1,1),
usr_name VARCHAR (30) NOT NULL,
f_name VARCHAR (30) NOT NULL,
l_name VARCHAR (30),
b_day DATE,
email VARCHAR (120) NOT NULL,
genderpkid VARCHAR (10) NOT NULL,
CONSTRAINT gender_fk FOREIGN KEY (genderpkid) REFERENCES gender (genderpk),
);
INSERT
INTO user_info
( usr_name, f_name, l_name, b_day, genderpkid, email)
VALUES
('JMAN', 'JOHN', 'DOE', '1990-01-01','M','EX#EMAIL'),
('JAM','JANE', 'DOE', '1995-05-02','F','EX#EMAIL'),
('NMAN','NICK', 'WEBB', '1999-06-22','M','EX#EMAIL'),
('LOBA','LOLA', 'LILLY', '1994-01-08','F','EX#EMAIL'),
('NOTSPMAN','PETER', 'PARKER','1985-11-25','M','EX#EMAIL');
SELECT * FROM user_info;

Your foreign key needs to reference the name of a table column (which is either id or gend) and not the name of the primary key (genderpk).
Therefore the foreign key script (CONSTRAINT gender_fk FOREIGN KEY (genderpkid) REFERENCES gender (genderpk)) should look something like CONSTRAINT gender_fk FOREIGN KEY (genderpkid) REFERENCES gender (id)
However to create the relationship the two columns need to have the same data type. user_info .genderpkid is VARCHAR (10) and user_info.id is int.
The other problem you might encounter is that the insert scripts insert the data into genderpkid column as M or F. Therefore int is not going to work
If you were to use use the values M or F for gender, then you can create a script like:
CREATE TABLE gender (
id VARCHAR (1),
gender VARCHAR (20)
CONSTRAINT gender_pk PRIMARY KEY (id)
);
CREATE TABLE user_info (
id int PRIMARY KEY IDENTITY (1,1),
usr_name VARCHAR (30) NOT NULL,
f_name VARCHAR (30) NOT NULL,
l_name VARCHAR (30),
b_day DATE,
email VARCHAR (120) NOT NULL,
genderId VARCHAR (1) NOT NULL,
CONSTRAINT gender_fk FOREIGN KEY (genderId) REFERENCES gender (id),
);
INSERT INTO gender (id, gender)
VALUES
('F', 'Female'),
('M', 'Male')
INSERT
INTO user_info
( usr_name, f_name, l_name, b_day, genderId, email)
VALUES
('JMAN', 'JOHN', 'DOE', '1990-01-01','M','EX#EMAIL'),
('JAM','JANE', 'DOE', '1995-05-02','F','EX#EMAIL'),
('NMAN','NICK', 'WEBB', '1999-06-22','M','EX#EMAIL'),
('LOBA','LOLA', 'LILLY', '1994-01-08','F','EX#EMAIL'),
('NOTSPMAN','PETER', 'PARKER','1985-11-25','M','EX#EMAIL');
SELECT * FROM user_info;
A better approach could be, to pass the whole phraze (male / female) to the table user_info. The table gender can be used to enforce referential integrity. All your information is then contained in SELECT * FROM user_info
For example:
CREATE TABLE gender (
[name] VARCHAR (20)
CONSTRAINT gender_pk PRIMARY KEY ([name])
);
CREATE TABLE user_info (
id int PRIMARY KEY IDENTITY (1,1),
usr_name VARCHAR (30) NOT NULL,
f_name VARCHAR (30) NOT NULL,
l_name VARCHAR (30),
b_day DATE,
email VARCHAR (120) NOT NULL,
gender VARCHAR (20) NOT NULL,
genderIntrest VARCHAR (20) NOT NULL,
CONSTRAINT gender_fk FOREIGN KEY (gender) REFERENCES gender ([name]),
CONSTRAINT genderIntrest_fk FOREIGN KEY (genderIntrest) REFERENCES gender ([name]),
);
INSERT INTO gender ([name])
VALUES
('Female'),
('Male')
INSERT
INTO user_info
( usr_name, f_name, l_name, b_day, gender, genderIntrest, email)
VALUES
('JMAN', 'JOHN', 'DOE', '1990-01-01','Male','Female', 'EX#EMAIL'),
('JAM','JANE', 'DOE', '1995-05-02','Female','Female', 'EX#EMAIL'),
('NMAN','NICK', 'WEBB', '1999-06-22','Male','Female','EX#EMAIL'),
('LOBA','LOLA', 'LILLY', '1994-01-08','Female','Female','EX#EMAIL'),
('NOTSPMAN','PETER', 'PARKER','1985-11-25','Male','Female','EX#EMAIL');
SELECT * FROM user_info;
You can remove the gender table and let the app that consumes it pass in the data. However for a learning exercises, it's probably better to leave it in

Related

How can i solve the unique constraint error in sql program?

I have homework to create tables and insert data into it and when i insert data into Branch table it gives me a unique constraint error and I don’t know why, and how can I solve this problem. my codes:
create table Branch(
Branchno varchar (4) primary key not null,
Street varchar (15) not null,
City varchar (10) not null,
Postcode varchar (10) not null)
create table staff (
Staffno varchar (4),
Fname varchar2 (50) not null,
Lname varchar (50),
Position varchar2 (50),
Sex varchar (1),
Dob date,
Salary number (30),
Branchno varchar (4),
constraint pk_staff primary key (staffno),
constraint fk_staff_branchno foreign key (branchno)
references Branch (branchno)
)
create table Client
(Clientno varchar (4) primary key not null,
Fname varchar (50) not null,
Lname varchar (50) not null,
Telno varchar (50) not null,
Preftype varchar (18) not null,
Maxrent INT)
create table PropertyForRent(
Propertyno varchar (40) not null,
Street varchar (40),
City varchar (40),
Postcode varchar (40),
Type varchar (40),
Rooms number (30),
Rent number (30),
Ownerno varchar (40),
Staffno varchar (40),
Branchno varchar (40),
constraint pk_PropertyForRent primary key (Propertyno),
foreign key (staffno)
references staff (staffno),
foreign key (branchno)
references branch (branchno)
)
create table Registration
(clientno varchar (60) not null,
branchno varchar (50) not null,
staffno varchar (50) not null,
datejoined date not null,
foreign key (clientno) references client (clientno),
foreign key (branchno) references branch (branchno),
foreign key (staffno) references staff (staffno)
)
The data that I insert to give me this error:
INSERT INTO Branch values
('B005','22 Deer Rd','London','SW1 4EH');
INSERT INTO Branch values
('B007','16 Argy11 St','Aberdeen','AB2 3SU');
I try with Oracle 11g and not receive any error:
SQL> INSERT INTO Branch values
('B005','22 Deer Rd','London','SW1 4EH'); 2
1 row created.
SQL> INSERT INTO Branch values
('B007','16 Argy11 St','Aberdeen','AB2 3SU'); 2
1 row created.
SQL> commit;
Commit complete.
Probably have you already record with these keys or have you any trigger on this table.
Instead of an INSERT INTO
you could
MERGE INTO Branch dest
USING( SELECT 'B005' Branchno,'22 Deer Rd' Street,'London' City,'SW1 4EH' Postcode FROM dual) src
ON( dest.Branchno = src.Branchno )
WHEN NOT MATCHED THEN
INSERT( Branchno, Street, City,Postcode )
VALUES ( src.Branchno, src.Street, src.City,src.Postcode );
That looks on the first sight, more difficult, but you would not get an error and all stops.
trggers can't stop you from inserting doulbe entires as they you can only can raise errors with wuld stop again every multi insert
see example

SQL: "foreign key constraint fails" error message

I get an error when attempting to insert data into the songs table. I'm not sure why.
Any help would be greatly appreciated. Thanks. This is me adding details so it will let me post haha.
create table artist
(
id int primary key auto_increment,
name varchar(128) not null,
nationality varchar(128)
) ENGINE=InnoDB;
insert into artist (name, nationality) values ('Metallica', 'American');
insert into artist (name, nationality) values ('Rush', 'Canadian');
create table album
(
id int primary key auto_increment,
name varchar (128) not null,
artist int not null,
foreign key (artist) references artist(id),
genre int,
foreign key (genre) references genre(id)
) ENGINE=InnoDB;
insert into album (name, artist, genre) values ('Ride the Lightning', 1, 1);
insert into album (name, artist, genre) values ('Moving Pictures', 2, 2);
create table song
(
id int primary key auto_increment,
name varchar (128) not null,
duration varchar (128),
album int not null,
foreign key (album) references album(id)
) ENGINE=InnoDB;
insert into song (name, duration, album) values ('Fade to Black', '1 min', 1);
insert into song (name, duration, album) values ('Tom Sawyer', '2 min', 2);
create table genre
(
id int primary key auto_increment,
name varchar (128) not null,
description varchar (256)
) ENGINE=InnoDB;
insert into genre (name, description) values ('Rock', 'Lots of drums and guitars');
insert into genre (name, description) values ('Metal', 'Drums and guitars on steroids');
The order of your code is causing the problem. You need to move the
create table genre
(
id int primary key auto_increment,
name varchar (128) not null,
description varchar (256)
) ENGINE=InnoDB;
insert into genre (name, description) values ('Rock', 'Lots of drums and guitars');
insert into genre (name, description) values ('Metal', 'Drums and guitars on steroids');
Up above the "Create table album"
Here is the correct way to do it: HOW TO DO IT
This is some reasons why it did not work:
There is no table "genre" when you try to create table album:
create table album
(
id int primary key auto_increment,
name varchar (128) not null,
artist int not null,
foreign key (artist) references artist(id),
genre int,
foreign key (genre) references genre(id)
) ENGINE=InnoDB;
Here is the DEMO
Also, when you create table "genre" on time, there is another problem. You have to insert data in table "genre" to be able to insert other data.
Here is the DEMO where all works.
One is the order of the create and insert statements shouldve given you error already as table referres doesnt exists etc.
Assuming if the order is rightly implemented, as per the above error not able to insert data in songs is likely because
Your album table has a null id or id which you are inserting in songs doesnt exists in album first insert the data in album table then insert into songs table as the foreign key of songs table is checking the album table for id data

How to make (patient id) forgein key in table of bill?

I try to create three tables by using website suport compiler any code but I have a problem in the table of the bill.
When I run it I get to error show me it is near in foreign key
These are codes of three tables
CREATE TABLE patient (
Patient Id (5) Primary key,
Name Varchar (20) Not null ,
Age Int Not null ,
Weight Int Not null ,
Gender Varchar (10) Not null,
Address Varchar (50) Not null ,
Disease Varchar (20) Not null
);
CREATE TABLE doctors (
DoctorId Varchar (5) Primary key,
Doctorname Varchar (15) Not null,
Dept Varchar (15) Not null
);
CREATE TABLE bill (
Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5) Foreign key,,
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null
);
Patient Table
CREATE TABLE patient
(
patient_id VARCHAR (5) PRIMARY KEY,
name VARCHAR (20) NOT NULL,
age INT NOT NULL,
weight INT NOT NULL,
gender VARCHAR (10) NOT NULL,
address VARCHAR (50) NOT NULL,
disease VARCHAR (20) NOT NULL
);
Errors
No data type has been assigned in Patient id column (Patient Id (5)
Primary key)
Patient id column name contains spaces. You need to
enclose the column name in double quotes or replace space with something else
(ex: _). It's not recommended to use spaces.
A column name with space
CREATE TABLE tablename ("column name" datatype);
Doctors Table
CREATE TABLE doctors
(
doctorid VARCHAR (5) PRIMARY KEY,
doctorname VARCHAR (15) NOT NULL,
dept VARCHAR (15) NOT NULL
);
Bill Table
CREATE TABLE bill
(
bill_no VARCHAR (50) PRIMARY KEY,
patient_id VARCHAR (5),
doctor_charge INT NOT NULL,
patient_type VARCHAR (10) NULL,
no_of_days INT NULL,
lab_charge INT NULL,
bill INT NOT NULL,
FOREIGN KEY (patient_id) REFERENCES patient(patient_id)
);
Errors
The way you have assigned foreign key is wrong. Please refer this and this article for more information. (Patient_Id Varchar (5) Foreign key,,)
There are two commans in the Patient_Id column (Patient_Id Varchar (5) Foreign key,,)
You have to provide reference of the table for which you want to use the reference key.
For example, you have table Persons which has Primary key PersonID, in that case if you want to use that as foreign key in another table, lets say Orders.
In Oracle
CREATE TABLE Orders (
OrderID numeric(10) not null,
OrderNumber numeric(10) not null,
PersonID numeric(10) not null,
CONSTRAINT fk_person_id
FOREIGN KEY (PersonID )
REFERENCES Persons(PersonID )
Your Case :
CREATE TABLE bill
( Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5),
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null,
CONSTRAINT fk_patient_id
FOREIGN KEY (Patient_Id)
REFERENCES patient(Patient_Id)
);
Remove the 'Foreign Key' from the table creation script.
Add this to your SQL script:
ALTER TABLE [Bill] WITH CHECK ADD CONSTRAINT [FK_Bill_Patient] FOREIGN KEY([Patient_Id])
REFERENCES [Patient] ([Patient_Id])
GO
ALTER TABLE [Bill] CHECK CONSTRAINT [FK_Bill_Patient]
GO
The words FOREIGN KEY are only needed for introducing the name of the FK constraint. Since your other constraints are not named, you might as well skip that part and go straight to REFERENCES.
If you specify a foreign key constraint as part of the column definition, you can omit the datatype to allow it to inherit from its parent at the time of creation, which I think is good practice as the types will automatically match.
We use VARCHAR2 in Oracle, not VARCHAR.
You don't need to specify NULL for columns that are allowed to be null.
I am not sure a 5-character string is a good datatype for a unique ID. How will you generate the values? Normally an auto-incrementing sequence number simplifies this.
create table doctors
( doctorid varchar2(5) primary key
, doctorname varchar2(15) not null
, dept varchar2(15) not null );
create table patients
( patient_id varchar2(5) primary key
, name varchar2(20) not null
, age integer not null
, weight integer not null
, gender varchar2(10) not null
, address varchar2(50) not null
, disease varchar2(20) not null );
create table bills
( bill_no varchar2(50) primary key
, patient_id references patients -- Allow datatype to inherit from parent
, patient_type varchar2(10)
, no_of_days integer
, lab_charge integer
, bill integer not null );

Foreign Key issue SQL

I cant figure out why this is not compiling It has to do with the foreign key somehow:
Drop Table Employee;
Drop Table Department;
Create Table Employee(
EmpNr int not null primary key,
EmpName Varchar(35) not null,
Dept Varchar (2) not null,
Gender char not null
);
Create Table Department(
DeptCode Varchar (2) not null primary key,
DeptName Varchar (35) not null,
Foreign Key (DeptCode) references Employee (Dept)
);
insert into Employee values (001, 'HagarT','DV','M'),
(002, 'WongS','DV','F'),
(003, 'Jones','MK','F'),
(004, 'MifuneK','SL','M');
insert into Department values ('DV', 'Development'),
('MK', 'Marketing'),
('RS', 'Research'),
('SL', 'Sales');
You need Dept be PRIMARY KEY or UNIQUE to work as FK
Create Table Employee(
EmpNr int not null primary key,
EmpName Varchar(35) not null,
Dept Varchar (2) unique not null,
Gender char not null
);
As you can see your Employee has two rows with 'DV' so which will be foreign for the Department?
I think you want is
Create Table Employee(
EmpNr int not null primary key,
EmpName Varchar(35) not null,
Dept Varchar (2) not null,
Gender char not null,
Foreign Key (Dept) references Department (DeptCode)
);

I want to update an existing record how do i do?

I have 3 tables:
CREATE TABLE employee(
presismail varchar(50) NOT NULL,
name varchar (50),
lastname varchar (50),
CONSTRAINT presismail PRIMARY KEY (presismail))
CREATE TABLE users(
usermail varchar(50)NOT NULL,
nomail varchar (2),
CONSTRAINT usermail PRIMARY KEY (usermail))
CREATE TABLE assignment(
presismail varchar(50)NOT NULL,
usermail varchar(50)NOT NULL,
senddates varchar (20)NOT NULL,
answervalue varchar (3),
receivedates varchar (20)
CONSTRAINT PK_assignment PRIMARY KEY (presismail, usermail, senddates),
FOREIGN KEY (presismail) REFERENCES employee(presismail),
FOREIGN KEY (usermail) REFERENCES users(usermail))
I want to create a storedprocedure that adds values into 2 columns that has been selected.
insert into assignment(answervalue, receivedates)
values (#answervalue, #receivedates)
select answervalue, receivedates
from assignment
where presismail = #presismail
and usermail = #usermail
and senddates = #senddates
How can i do that?
i think you want to update an existing record,
UPDATE assignment
SET answervalue = #answervalue,
receivedates = #receivedates
WHERE presismail = #presismail
AND usermail = #usermail
AND senddates = #senddates
Try this.
insert into assignment(answervalue, receivedates)
select answervalue, receivedates
from assignment
where --------