relationship many to many - sql-server

I want to create database with relationship many to many. But i have error
SQL71516 :: The referenced table '[dbo].[BookAuthors]' 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. SQL71516 :: The referenced table
'[dbo].[BookAuthors]' 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 to fix this?
CREATE TABLE [dbo].[BookAuthors] (
[Book] INT NOT NULL,
[Author] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Book] ASC,[Author] ASC)
);
CREATE TABLE [dbo].[Books] (
[Id] INT NOT NULL,
[Title] NVARCHAR (MAX) NULL,
[Price] MONEY NULL,
[Category] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
FOREIGN KEY ([Id]) REFERENCES [dbo].[BookAuthors] ([Book])
);
CREATE TABLE [dbo].[Authors] (
[Id] INT NOT NULL,
[Name] NCHAR (10) NOT NULL,
PRIMARY KEY CLUSTERED ([Id]),
FOREIGN KEY ([Id]) REFERENCES [dbo].[BookAuthors] ([Author])
);

You crated in you BookAuthors composite primary key which consists of two columns: Book and Author. When referencing it, you need to reference both columns.
Other solution is to make in BookAuthors third column (identity maybe) which would be primary key and reference that one.

The Following Image Shows you the Table Structure.

Related

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
) ;

Entity Framework 6 Database First Doesn't Generate Entity on Table With Composite Key

Suppose I have the following table definition with a composite primary key:
create table [dbo].[CustomerRequests] (
[CustomerId] int not null,
[RequestId] int not null,
constraint [PK_CustomerRequests] primary key clustered ([CustomerId] asc, [RequestId] asc),
constraint [FK_CustomerRequests_Customers] foreign key ([CustomerId]) references [dbo].[Customers] ([CustomerId]),
constraint [FK_CustomerRequests_Requests] foreign key ([RequestId]) references [dbo].[Requests] ([RequestId])
);
When I update the model to include this table, Entity Framework fails to generate the entity class. Is this due to the composite primary key? Is there any way to make Entity Framework generate the entity class?
Gert Arnold's comment pointed me in the right direction, as did this answer.
Once I added another column besides the two primary keys, Entity Framework generated the entity. Here is a sample table definition for which EF Database First will create an entity:
create table [dbo].[CustomerRequests] (
[CustomerId] int not null,
[RequestId] int not null,
[TimestampUtc] datetime not null,
constraint [PK_CustomerRequests] primary key clustered ([CustomerId] asc, [RequestId] asc),
constraint [FK_CustomerRequests_Customers] foreign key ([CustomerId]) references [dbo].[Customers] ([CustomerId]),
constraint [FK_CustomerRequests_Requests] foreign key ([RequestId]) references [dbo].[Requests] ([RequestId])
);

SQL Relation MORE on MORE

I have a question about this relation betweed SpelerTeam and Toernooi, i get a error, can someone help me with it all the other relations do work:
Msg 1776, Level 16, State 0, Line 2 There are no primary or candidate
keys in the referenced table 'SpelerTeam' that match the referencing
column list in the foreign key 'FK__Toernooi__team__1A14E395'. Msg
1750, Level 16, State 0, Line 2 Could not create constraint. See
previous errors.
CREATE TABLE dbo.LoginGegevens
(
Username varchar(25) NOT NULL,
Wachtwoord varchar(25) NOT NULL,
LoginDatum date NOT NULL,
)
CREATE TABLE dbo.NawGegevensKind
(
KindSpeler varchar(25) NOT NULL,
NawKind varchar(50) NOT NULL,
)
CREATE TABLE dbo.NawGegevensProfspeler
(
Profspeler varchar(25) NOT NULL,
NawProfspeler varchar(50) NOT NULL,
)
CREATE TABLE dbo.SpelerTeam
(
Team int NOT NULL,
Kindspeler varchar(25) NOT NULL,
Profspeler varchar(25) NOT NULL,
)
CREATE TABLE dbo.Toernooi
(
team int NOT NULL,
score int NOT NULL,
games int NOT NULL,
rondes int NOT NULL,
)
-- primary keys
ALTER TABLE LoginGegevens
ADD primary KEY (Username)
ALTER TABLE NawGegevensKind
ADD primary KEY (KindSpeler)
ALTER TABLE NawGegevensProfspeler
ADD primary KEY (ProfSpeler)
ALTER TABLE SpelerTeam
ADD primary KEY (Team,KindSpeler,ProfSpeler)
ALTER TABLE Toernooi
ADD primary KEY (Team,Rondes,Games)
-- relation
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Kindspeler)
REFERENCES NawGegevensKind(Kindspeler);
ALTER TABLE SpelerTeam
ADD FOREIGN KEY (Profspeler)
REFERENCES NawGegevensProfspeler(Profspeler);
ALTER TABLE Toernooi
ADD FOREIGN KEY (Team)
REFERENCES SpelerTeam(Team);
The Primary Key of SpelerTeam is Team,KindSpeler,ProfSpeler.
That means that any foreign key that references that table has to reference all three of those columns. You can't create a foreign key that uses only team.
You need an index on a colum so that it can be referenced as a foreign key efficiently. Add an index on SpelerTeam.Team and on all other columns with the same problem. Try CREATE INDEX IX_SpelerTeam_Team_Team ON SpelerTeam (Team);
Add below after all tables have been created:
CREATE UNIQUE NONCLUSTERED INDEX IX_SpelerTeam_Team
ON dbo.SpelerTeam (Team);
GO
As it was pointed in another answer you cannot reference to non unique column, to make column unique you can make this column primary key or create index for this column.
It is not enough that your "Team" column is part of composite key.

SQL Server foreign relationship on two-column primary key

I have the following three sample tables (simplified demo for purpose of question):
CREATE TABLE Teams
(
Id int IDENTITY(1,1) NOT NULL,
Name varchar(50) NOT NULL,
PRIMARY KEY (Id)
)
CREATE TABLE TeamGroups
(
Id int NOT NULL,
TeamId int NOT NULL,
PRIMARY KEY (Id,TeamId)
)
CREATE TABLE RoomBookings
(
Id int NOT NULL,
TeamGroupId int NOT NULL,
RoomId int NOT NULL,
PRIMARY KEY (Id)
)
and I have the following foreign key already set up:
ALTER TABLE TeamGroups WITH CHECK
ADD CONSTRAINT [FK_TeamGroups_Teams]
FOREIGN KEY (TeamId) REFERENCES Teams(Id)
The idea is that each Team can be in zero or more TeamGroups, and each TeamGroup can have zero or more RoomBookings
To reflect that, I want to add a foreign key from the RoomBookings table into the TeamGroups table.
I tried using the Relationships GUI in Management Studio to create the foreign key (primary key table: TeamGroups.ID, foreign key table: RoomBookings.TeamGroupId) but I get an error:
The columns in table 'TeamGroups' do not match an existing primary key
or UNIQUE constraint
I'm assuming it's because the TeamGroups table has a two-column primary key?
I don't really want to make a foreign key constraint from the TeamGroups table (eg, the key is present in the TeamGroups table), as the table will eventually be used by other tables (such as EquipmentBookings, GroupManagers, etc).
Any help?
If your primary key is made up from more than one columns, then all foregin keys also must have all those columns - there's no way around this.
But I don't understand why you'd get this error trying to link TeamGroups to Team based on the Team.Id column.... that should work just fine.
Try using this:
ALTER TABLE TeamGroups WITH CHECK
ADD CONSTRAINT [FK_TeamGroups_Teams]
FOREIGN KEY (TeamId) REFERENCES Teams(Id);
You had Teams (which is not a valid column in TeamGroups at all), and you had REFERENCES Teams.id which is wrong - it needs to be REFERNCES Teams(Id); (column in parenthesis - not the "dot" notation)
Update: from TeamGroups to RoomBookings - yes.... either use both columns from TeamGroups in your RoomBookings table - or what would stop you from making the TeamGroups.Id column an INT IDENTITY and then have the PK on just this one column?? Any good reason for that??
CREATE TABLE TeamGroups
(
TeamGroupId int NOT NULL,
TeamId int NOT NULL,
PRIMARY KEY (TeamGroupId)
)
ALTER TABLE dbo.RoomBookings
ADD CONSTRAINT FK_RoomBookings_TeamGroup
FOREIGN KEY TeamGroupId REFERENCES TeamGroups(TeamGroupId)

How can I delete child rows when I delete a parent row in SQL Server?

I have two tables:
CREATE TABLE [dbo].[AdminTest] (
[AdminTestId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (100) NOT NULL,
CONSTRAINT [PK_AdminTest] PRIMARY KEY CLUSTERED ([AdminTestId] ASC)
);
GO
CREATE NONCLUSTERED INDEX [Test_ExamId_IX]
ON [dbo].[AdminTest]([ExamId] ASC);
CREATE TABLE [dbo].[AdminTestQuestion] (
[AdminTestQuestionId] INT IDENTITY (1, 1) NOT NULL,
[AdminTestId] INT NOT NULL,
[QuestionUId] UNIQUEIDENTIFIER NOT NULL,
CONSTRAINT [PK_AdminTestQuestion] PRIMARY KEY CLUSTERED ([AdminTestQuestionId] ASC),
CONSTRAINT [FK_AdminTestQuestionAdminTestId] FOREIGN KEY ([AdminTestId]) REFERENCES [dbo].[AdminTest] ([AdminTestId])
);
GO
CREATE NONCLUSTERED INDEX [AdminTestQuestion_AdminTestId_IX]
ON [dbo].[AdminTestQuestion]([AdminTestId] ASC);
Is there some way that I can change the definition of the tables so that when I delete a row from AdminTest then all the child rows in AdminTestQuestions for that test are deleted?
You can add ON DELETE CASCADE to your foreign key constraint;
CONSTRAINT [FK_AdminTestQuestionAdminTestId]
FOREIGN KEY ([AdminTestId]) REFERENCES [dbo].[AdminTest] ([AdminTestId])
ON DELETE CASCADE
An SQLfiddle to test with.
I may not need to point out that this is not necessarily a good idea in the long run, since it will make implicit changes to your data that other users may not know about. Use with caution.

Resources