I have two tables - Educators and Faculties:
CREATE TABLE [dbo].[Educators]
(
[UserId] [nvarchar](128) NOT NULL,
[FacultyId] [smallint] NOT NULL,
[InstitutionUserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_Educators]
PRIMARY KEY CLUSTERED ([UserId] ASC)
)
CREATE TABLE [dbo].[Faculties]
(
[InstitutionUserId] [nvarchar](128) NOT NULL,
[FacultyId] [smallint] NOT NULL,
CONSTRAINT [PK_UserFaculties]
PRIMARY KEY CLUSTERED ([InstitutionUserId] ASC, [FacultyId] ASC)
)
The table Faculties has a compound primary key made up from two columns (InstitutionUserId and FacultyId). I also have the same column in the Educators table. I want to link those two tables together with a foreign key.
So, this is my query:
ALTER TABLE [dbo].[Educators] WITH CHECK
ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId]
FOREIGN KEY ([FacultyId], [InstitutionUserId])
REFERENCES [dbo].[Faculties] ([FacultyId], [InstitutionUserId])
But I getting this error message:
Msg 1776, Level 16, State 0, Line 7
There are no primary or candidate keys in the referenced table 'dbo.Faculties' that match the referencing column list in the foreign key 'FK_Educators_FacultyId_Faculties_FacultyId'.
Msg 1750, Level 16, State 1, Line 7
Could not create constraint or index. See previous errors.
How to solve this problem?
Your tables and their constraints look fine. The only issue I can see is that the order of the columns in your primary key
CONSTRAINT [PK_UserFaculties] PRIMARY KEY CLUSTERED
(
[InstitutionUserId] ASC,
[FacultyId] ASC
)
is different from the order that you've declared in your foreign key constraint
ALTER TABLE [dbo].[Educators] WITH CHECK ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] FOREIGN KEY([FacultyId], [InstitutionUserId])
REFERENCES [dbo].[Faculties] ([FacultyId], [InstitutionUserId])
Try changing the order of the columns in the declaration of your foreign key like this:
ALTER TABLE [dbo].[Educators] WITH CHECK ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] FOREIGN KEY([InstitutionUserId], [FacultyId])
REFERENCES [dbo].[Faculties] ([InstitutionUserId], [FacultyId])
The keys should be in the same order that they are defined:
ALTER TABLE dbo.Educators
ADD CONSTRAINT FK_Educators_FacultyId_Faculties_FacultyId
FOREIGN KEY(InstitutionUserId, FacultyId)
REFERENCES dbo.Faculties(InstitutionUserId, FacultyId);
Related
I'm creating a SQL table in VS that stores what rooms each client is, So the table has RoomId (int) and UserID (int).
Because I only want to add to the table only rooms and clients that exist they are both keys that have a foreign key to 2 tables, one that stores RoomID and Name and another that stores Client ID and Name.
Room and UserId tables:
CREATE TABLE [dbo].[UsersInRoomsTable]
(
RoomId INT NOT NULL,
UserId INT NOT NULL,
CONSTRAINT PK_RS PRIMARY KEY(RoomId, UserId),
CONSTRAINT [fk_room] FOREIGN KEY([RoomId]) REFERENCES [dbo].[RoomsTable]([RoomId]),
CONSTRAINT [fk_user] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfoTable] ([UserId])
);
Table that stores all the users:
CREATE TABLE [dbo].[UserInfoTable]
(
[UserName] NVARCHAR (50) NOT NULL,
[UserId] INT NOT NULL,
CONSTRAINT [PK_roomuser] PRIMARY KEY CLUSTERED ([UserName] ASC, [UserId] ASC)
);
Table that stores all the rooms
CREATE TABLE [dbo].[RoomsTable]
(
[RoomId] INT NOT NULL,
[RoomName] NVARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([RoomId] ASC)
);
Everything works except the last line in the Rooms and users table:
CONSTRAINT [fk_user] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfoTable] ([UserId])
When I try to Update the table I get an error SQL71516:
SQL71516: The referenced table '[dbo].[UserInfoTable]' contains no primary or candidate keys that match the referencing column list in the foreign key.
If the referenced column is a computed column, it should be persisted
How can I solve this problem and what is causing it?
Edit: I think I know what is code is colliding: For some reason I can not have a foreign key connecting to a key that contains 2 indexes IE: fk_user is a Fk to table UserInfoTable that has 2 keys (UserID and UserName)
is there a way to pass this obstacle?
The columns of a foreign key have to match the columns they reference by number, type and order.
You have a primary key on userinfotable of (username, userid). But in usersinroomstable you are trying to let the foreign key (userid) to reference that. The number of columns doesn't match, so the foreign key cannot be added.
Presumably the username shouldn't really be part of the primary key of userinfotable and got there by accident. Remove it from the primary key constraint.
Or, if username has to be in the primary key, add such a column to the table usersinroomstable and add it to the foreign key constraint.
when I execute my reservation table query, I get an error.
Any help?
This is my reservation table query
CREATE TABLE RESERVATION
(
NUMCHAMBRE INT FOREIGN KEY REFERENCES CHAMBRE (NUMCHAMBRE) ,
NUMHOTEL INT FOREIGN KEY REFERENCES HOTEL (NUMHOTEL),
NUMCLIENT INT FOREIGN KEY REFERENCES CLIENT (NUMCLIENT),
DATEARRIVE DATE,
DATEDEPART DATE,
PRIMARY KEY (NUMHOTEL, NUMCLIENT, DATEARRIVE)
);
This is the error I get:
Msg 1776, Level 16, State 0, Line 2
There are no primary or candidate keys in the referenced table 'CHAMBRE' that match the referencing column list in the foreign key 'FK__RESERVATI__NUMCH__2BFE89A6'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint or index. See previous errors.
According to your comment, the primary key on chambre is composite. So the foreign key reference needs to include all the columns:
CREATE TABLE RESERVATION (
NUMCHAMBRE int,
NUMHOTEL int Foreign Key REFERENCES HOTEL (NUMHOTEL),
NUMCLIENT int Foreign Key REFERENCES CLIENT (NUMCLIENT),
DATEARRIVE date,
DATEDEPART date,
foreign key (numhotel, numchambre) references chambre (numhotel, numchambre);
)
The column NUMCHAMBRE you're referencing in table CHAMBRE must be a primary key column, i.e. you can't just reference any column.
You can declare it as the primary key like this:
alter table CHAMBRE add primary key (NUMCHAMBRE);
Primary key columns need to be not null, so if NUMCHAMBRE is nullable, the above command will fail.
Update:
Based on your comment below, your table definition should be like this, i.e. you need to reference both columns of the primary key:
CREATE TABLE RESERVATION (
NUMCHAMBRE int,
NUMHOTEL int not null Foreign Key REFERENCES HOTEL (NUMHOTEL),
NUMCLIENT int not null Foreign Key REFERENCES CLIENT (NUMCLIENT),
DATEARRIVE date not null,
DATEDEPART date,
PRIMARY KEY (NUMHOTEL,NUMCLIENT,DATEARRIVE),
Foreign Key (NUMCHAMBRE,NUMHOTEL) REFERENCES CHAMBRE (NUMCHAMBRE,NUMHOTEL)
);
Note the additional not null constraints, as these will be necessary in order to create the primary key on this table using SQL Server.
I have forgot create a primary key for my table. Now I want to update the DocDay_Id column and make it the primary key. How can I do it?
My code is below.
I tried this syntax but it is not correct.
ALTER TABLE DoctorDays
ALTER COLUMN DocDay_Id int IDENTITY(1,1) PRIMARY KEY NOT NULL
Create table DoctorDays
(
DocDay_Id int IDENTITY(1,1) NOT NULL,
Doc_Id int FOREIGN KEY REFERENCES Doctor(Doc_Id) NOT NULL,
Day_Id int FOREIGN KEY REFERENCES Dayss(Day_Id) NOT NULL
)
To create a clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY CLUSTERED (DocDay_Id);
To create a non clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY NONCLUSTERED (DocDay_Id);
FIDDLE DEMO HERE
See the document in below link:
Alter Statement Documents
I am having a problem adding a foreign key constraint to SQL 2008 that is based on a composite primary key in another table. I have followed some directions based on a few posts on here, but haven't been able to get it to work.
I have two tables:
CREATE TABLE [Staging].[ActivityLog](
[ActivityLogId] [int] IDENTITY(1,1) NOT NULL,
...
[ActivityLogType] [varchar](10) NOT NULL,
[ActivityLogSubType] [varchar](10) NOT NULL,
CONSTRAINT [PK_ActivityLog] PRIMARY KEY CLUSTERED
(
[ActivityLogId] ASC
))
and
CREATE TABLE [Staging].[ActivityLogTypeSubType](
[ActivityLogType] [varchar](10) NOT NULL,
[ActivityLogSubType] [varchar](10) NOT NULL,
CONSTRAINT [PK_ActivityLogTypeSubType] PRIMARY KEY CLUSTERED
(
[ActivityLogType] ASC,
[ActivityLogSubType] ASC
))
GO
I am trying to add a foreign key like this:
ALTER TABLE Staging.ActivityLog
ADD CONSTRAINT FK_ActivityLog_ActivityLogTypeSubType
FOREIGN KEY(ActivityLogType, ActivityLogSubType)
REFERENCES Staging.ActivityLogTypeSubType(ActivityLogType, ActivityLogSubType)
I get this error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_ActivityLog_ActivityLogTypeSubType". The conflict occurred in database "HMDB_DEV", table "Staging.ActivityLogTypeSubType".
I have verified that this FK doesn't already exist.
I apologize for the lengthy post. Any help would be greatly appreciated.
Thanks,
James
Have you verified data to match FK logic?
I had to write the SQL to create the tables, attributes, and primary & foreign keys in this ERD:
http://imgur.com/VYZbwr6
In the table 'Financial_Transactions' in the ERD there is a attribute called 'previous_transaction_id' and another attribute called 'transaction_id'. In this table 'previous_transaction_id' is a Foreign Key for this table in addition to being an attribute. It references the last 'transaction_id' in the table.
Here is my SQL for the 'financial_transactions' table:
CREATE TABLE financial_transactions(
transaction_id int IDENTITY(1,1) NOT NULL,
account_id int NOT NULL,
item_rental_id int NOT NULL,
previous_transaction_id int,
transaction_type_code int NOT NULL,
transaction_date date NOT NULL,
transaction_amount money NOT NULL,
transaction_comment varchar(512) NOT NULL);
ALTER TABLE financial_transactions ADD CONSTRAINT pk_financial_transactions PRIMARY KEY (transaction_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_accounts FOREIGN KEY(account_id)
REFERENCES accounts (account_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_customer_rentals FOREIGN KEY(item_rental_id)
REFERENCES customer_rentals (item_rental_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_transaction_types FOREIGN KEY(transaction_type_code)
REFERENCES transaction_types (transaction_type_code);
When I run my SQL (includes statements for each table in the script) I get these errors:
"Msg 1776, Level 16, State 0, Line 87
There are no primary or candidate keys in the referenced table 'financial_transactions' that match the referencing column list in the foreign key 'fk_financial_transactions_financial_transactions'.
Msg 1750, Level 16, State 0, Line 87
Could not create constraint. See previous errors."
All other statements execute normally.
What am I doing wrong?
*I used this statement originally under CREATE TABLE: previous_transaction_id int NOT NULL,
However, it resulted in the same error and when searching I saw a similar question that was fixed by removing the NOT NULL.
Here
ALTER TABLE financial_transactions ADD CONSTRAINT
fk_financial_transactions_financial_transactions
FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
You have a column referencing itself. Was that your intent or did you want to reference the transaction_id?
There is nothing wrong with defining a foreign key to the same table but you have a column referencing itself.
Try replacing:
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (previous_transaction_id);
With:
ALTER TABLE financial_transactions ADD CONSTRAINT fk_financial_transactions_financial_transactions FOREIGN KEY(previous_transaction_id)
REFERENCES financial_transactions (transaction_id);