Foreign key error in SQL Server 2014 - sql

Sorry I had to be more specific in here. So following is SQL my code. Copy and paste in SQL. Basically, I am creating 13 tables that are linked together.
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='EventType')
BEGIN
DROP TABLE EventType
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='EventLocation')
BEGIN
DROP TABLE EventLocation
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='StudentEvent')
BEGIN
DROP TABLE StudentEvent
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Event')
BEGIN
DROP TABLE Event
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='CurrentAddress')
BEGIN
DROP TABLE CurrentAddress
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='PreviousAddress')
BEGIN
DROP TABLE PreviousAddress
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='ContactType')
BEGIN
DROP TABLE ContactType
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Contact')
BEGIN
DROP TABLE Contact
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='StudentMajor')
BEGIN
DROP TABLE StudentMajor
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Major')
BEGIN
DROP TABLE Major
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Citizenship')
BEGIN
DROP TABLE Citizenship
END
GO
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Country')
BEGIN
DROP TABLE Country
END
IF EXISTS (SELECT*FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Student')
BEGIN
DROP TABLE Student
END
GO
CREATE TABLE Student
(
StudentID int identity PRIMARY KEY,
FirstName varchar (50),
LastName varchar (30)
)
GO
CREATE TABLE Country
(
CountryID int identity PRIMARY KEY,
CountryOfBirth varchar (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID)
)
GO
CREATE TABLE Citizenship
(
CitizenshipID int identity PRIMARY KEY,
CountryOfCitizenship1 varchar (10),
CountryOfCitizenship2 varchar (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
CountryID int FOREIGN KEY REFERENCES Country(CountryID)
)
GO
CREATE TABLE Major
(
Majorid int identity PRIMARY KEY,
MajorName varchar(30),
GraduatedMajor varchar (30)
)
CREATE TABLE StudentMajor
(
StudentMajorid int identity,
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
MajorID int FOREIGN KEY REFERENCES Major(MajorID)
)
GO
ALTER TABLE StudentMajor
ADD constraint uk_sm UNIQUE (StudentID,MajorID)
CREATE TABLE Contact
(
ContactId int identity PRIMARY KEY,
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
ContactInfo varchar (8),
ContactDate datetime
)
GO
CREATE TABLE ContactType
(
ContactTypeId int identity PRIMARY KEY,
ContactID int FOREIGN KEY REFERENCES Contact(ContactID)
)
GO
CREATE TABLE PreviousAddress
(
PreviousAddressId int identity PRIMARY KEY,
Address1 varchar (50),
Address2 varchar (50),
City varchar (20),
State varchar (20),
Pincode char (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID)
)
GO
CREATE TABLE CurrentAddress
(
CurrentAddressId int identity PRIMARY KEY,
Address1 varchar (50),
Address2 varchar (50),
City varchar (20),
State varchar (20),
Pincode char (10),
StudentID int FOREIGN KEY REFERENCES Student(StudentID)
)
GO
CREATE TABLE EventType
(
EventTypeID int identity PRIMARY KEY
)
CREATE TABLE Event
(
EventId int identity PRIMARY KEY,
EventDate datetime,
EventTitle varchar (50),
EventTime datetime,
EventTypeID int
)
GO
ALTER TABLE Event
ADD constraint fk_Event
FOREIGN KEY (EventTypeID) REFERENCES EventType(EventTypeID)
CREATE TABLE StudentEvent
(
StudentEventId int identity PRIMARY KEY,
StudentID int FOREIGN KEY REFERENCES Student(StudentID),
EventID int FOREIGN KEY REFERENCES Event(EventID),
Comment varchar(2000)
)
GO
CREATE TABLE EventLocation
(
EventLocationId int identity PRIMARY KEY,
EventCountry varchar (50),
EventState varchar (50),
EventAddress1 varchar (100),
EventAddress2 varchar (100),
EventCity varchar (50),
EventPincode char (10),
EventID int FOREIGN KEY REFERENCES Event(EventID)
)
GO
Now the problem with the above code is that it will execute perfectly first time, but when I execute second time it throws me following error.
Could not drop object 'EventType' because it is referenced by a FOREIGN KEY constraint.
Msg 2714, Level 16, State 6, Line 132
There is already an object named 'EventType' in the database.
Msg 4902, Level 16, State 1, Line 143
Cannot find the object "Event" because it does not exist or you do not have permissions.
Msg 1767, Level 16, State 0, Line 153
Foreign key 'FK__EventLoca__Event__6265874F' references invalid table 'Event'.
Msg 1750, Level 16, State 0, Line 153
Could not create constraint or index. See previous errors.
Is there a better way to code the foreign key or am I doing something wrong.
Thanks in advance for help!

You should create the table first:
CREATE TABLE Event
(
EventId int identity PRIMARY KEY,
EventDate datetime,
EventTitle varchar (50),
EventTime datetime,
EventTypeID int
)
GO
CREATE TABLE EventType
(
EventTypeID int identity PRIMARY KEY
);
ALTER TABLE Event
ADD constraint fk_Event
FOREIGN KEY (EventTypeID) REFERENCES EventType(EventTypeID);
Or you can create your tables as:
CREATE TABLE EventType
(
EventTypeID int identity PRIMARY KEY
);
CREATE TABLE Event
(
EventId int identity PRIMARY KEY,
EventDate datetime,
EventTitle varchar (50),
EventTime datetime,
EventTypeID int,
constraint fk_Event FOREIGN KEY (EventTypeID) REFERENCES EventType(EventTypeID)
);
Update:
Could not drop object 'EventType' because it is referenced by a FOREIGN KEY constraint. Msg 2714, Level 16, State 6, Line 132 There is already an object named 'EventType' in the database. Msg 4902, Level 16, State 1, Line 143 Cannot find the object "Event" because it does not exist or you do not have permissions. Msg 1767, Level 16, State 0, Line 153 Foreign key 'FK__EventLoca__Event__6265874F' references invalid table 'Event'. Msg 1750, Level 16, State 0, Line 153 Could not create constraint or index. See previous errors.
This error msg is clear, you can't drop a table referenced in another table, so you have to drop the Event table first, then you can drop the EventsType table.

Try creating the table EventType before using it as a reference in the table Event.

Related

There are no primary or candidate keys in the referenced table 'tblgender' that match the referencing column list in the foreign key 'giFK'

create database my_data
create table tblperson(
pid int primary key,
pname varchar(15),
pgender varchar(15)
)
create table tblgender(
gid varchar(15) primary key,
gender varchar(15)
)
Alter table tblperson add constraint giFK
Foreign key (pgender) references tblgender(gid)

ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When creating the foreign key I came across this error. Below is my code.
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int
)
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
alter table tblPerson add constraint tblPerson_GenderId_FK
foreign key (GenderId) references tblGender(ID)
You want to identify any "do not align" rows....
I have made the below.
You won't be able to add the FK constraint, if any rows come back from the SELECT query.
I have also removed the hungarian notation for "tbl". I would advise against it.
create table dbo.Person(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int )
create table dbo.Gender (
ID int not null primary key,
Gender varchar(50) not null
)
/* any rows below? your FK creation will fail */
Select *, p.GenderId as 'HoustonWeHaveAProblemValue' from dbo.Person p Where Not Exists (Select 1 from dbo.Gender g where g.ID = p.GenderId)
alter table dbo.Person add constraint Person_GenderId_FK
foreign key (GenderId) references dbo.Gender(ID)
Hi please use the following code to achieve your goal :
1-First create tblGender:
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
2-Then create table tblPerson with the relationship between 2 tables since the beginning:
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int references tblGender(ID)
)
works fine.

SQL Server 2012 creating tables and values

For some odd reason I can't create a table and because if that I can't insert any values into those tables. This is a new database and I am having a bit of a brain fart.. any help??? thanks
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY (Agencies)
)
Example of a working code
create table Agencies
(
AgencyID nvarchar(20) primary key,
AgName nvarchar(40),
AgAddress nvarchar(40),
AgPhone int
)
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(20) FOREIGN KEY REFERENCES Agencies(AgencyID)
)
Hope it helps!
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY REFERENCES Agencies(Your_Agencies_ID_COLUMN)
)
There two ways of creating foreign key constrain:
creating a foreign key constraint within the table definition
CREATE TABLE [dbo].[DataSource]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Pts] TINYINT
,[PtsOf] TINYINT
, CONSTRAINT [PK_DataSource] PRIMARY KEY ([SurveyInstanceID], [ProtoQuestionID])
);
CREATE TABLE [dbo].[DataSourceComments]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Comments] NVARCHAR(MAX)
,CONSTRAINT [FK_DataSourceComments_DataSource_SurveyInstanceID_ProtoQuestionID]
FOREIGN KEY ([SurveyInstanceID], [ProtoQuestionID])
REFERENCES [dbo].[DataSource] ([SurveyInstanceID], [ProtoQuestionID])
);
creating a foreign key constraint for existing table
CREATE TABLE [dbo].[DataSource]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Pts] TINYINT
,[PtsOf] TINYINT
,CONSTRAINT [PK_DataSource] PRIMARY KEY ([SurveyInstanceID], [ProtoQuestionID] )
);
CREATE TABLE [dbo].[DataSourceComments]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Comments] NVARCHAR(MAX)
);
ALTER TABLE [dbo].[DataSourceComments]
ADD CONSTRAINT [FK_DataSourceComments_DataSource_SurveyInstanceID_ProtoQuestionID]
FOREIGN KEY ([SurveyInstanceID], [ProtoQuestionID])
REFERENCES [dbo].[DataSource] ([SurveyInstanceID], [ProtoQuestionID]);
Note, that in both cases I am specifying the FK constraint name. It's is a recommended to have some naming convention which to apply to all new FK.
I believe your foreign key is incorrect... maybe try this?
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY REFERENCES Agencies(AgencyID)
)
Supposing "AgencyID" is the ID in your Agencies Table.
Try the below code
CREATE TABLE Agency
(
AgencyID INT PRIMARY KEY IDENTITY,
Name NVARCHAR(20)
)
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID INT FOREIGN KEY REFERENCES Agency(AgencyID)
)
First you have to create the parent table ie, Agency table. Then create the child (Customers) and refer the parent.

SQL Server Foreign Key Constraint References Invalid Table

I have the following code:
CREATE TABLE _CLIENT
(
client_id int ,
client_name varchar(50),
type varchar(50),
constraint _CLIENT_pk PRIMARY KEY(client_id),
constraint _CLIENT_ch CHECK (client_id>0),
typee_id INT NOT NULL REFERENCES CLIENT_TYPE(typee_id)
)
CREATE TABLE CLIENT_TYPE
(
typee_id int NOT NULL,
name_type varchar(50),
constraint CLIENT_TYPE_pk PRIMARY KEY(typee_id)
)
The foreign key throws an error saying:
Foreign key 'FK__Number__Name__1CF15040' references invalid table 'Users.Name'
what's the wrong here?
I don't know what exact error message you are getting, but you have error in the current script and I think you mean this error:
Foreign key 'FK___CLIENT__typee_i__55BFB948' references invalid table
'CLIENT_TYPE'.
You should first create CLIENT_TYPE table, so the script should look like:
CREATE TABLE CLIENT_TYPE
(
typee_id INT NOT NULL ,
name_type VARCHAR(50) ,
CONSTRAINT CLIENT_TYPE_pk PRIMARY KEY ( typee_id )
)
CREATE TABLE _CLIENT
(
client_id INT ,
client_name VARCHAR(50) ,
type VARCHAR(50) ,
CONSTRAINT _CLIENT_pk PRIMARY KEY ( client_id ) ,
CONSTRAINT _CLIENT_ch CHECK ( client_id > 0 ) ,
typee_id INT NOT NULL
REFERENCES CLIENT_TYPE ( typee_id )
)
As a general rule, you should first create base tables and then tables which depend on those ones.

Why is the foreign key not accepted?

Why is the table Room not accepting the foreign key?
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3)
)
ALTER TABLE Room
add foreign key(Roomtype)
references RoomType(Roomtype)
This is the error message I get when I run alter table.
Major Error 0x80040E11, Minor Error 0
ALTER TABLE Room
add foreign key(Roomtype)
references RoomType(Roomtype)
Invalid column ID. [ Roomtype ]
You need to add the foreign key as a field to the Room table before you attempt to declare the foreign key constraint.
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3)
)
ALTER TABLE Room
ADD Roomtype nvarchar(2) NOT NULL
ALTER TABLE Room
add constraint FK_Give_Me_A_Good_Name foreign key(Roomtype)
references RoomType(Roomtype)
The column must exist BEFORE you can FK to it.
CREATE TABLE RoomType (
Roomtype nvarchar(2) NOT NULL,
Description nvarchar(20),
Responsibility nvarchar(20),
primary key (Roomtype)
)
Create table Room (
RoomID nvarchar(2) NOT NULL,
Capacity numeric(3),
RoomtypeA nvarchar(2) NOT NULL
)
ALTER TABLE [dbo].[Room] ADD CONSTRAINT FK_MyName FOREIGN KEY (RoomtypeA) REFERENCES dbo.Roomtype (Roomtype)
GO