SQL Server & Visual Studio - Insert Data in tables doesn't work - sql-server

I want to insert my tables from my SQL Server Management Studio code with data via Visual Studio.
But it doesn't work. The ID of my table doesn't get a value automatically (but I have command it with identity(1,1)) and an error appears that it stands in conflict with a foreign-key-constraint.
create table [ProduktZahlungFENutzer]
(
ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
Endpreis decimal(3, 2)
);
CREATE TABLE [FHAngehörige]
(
FHAngehörigeID INT NOT NULL IDENTITY(1,1)
PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE [FENutzer]
(
FENutzerID INT IDENTITY(1,1) NOT NULL
PRIMARY KEY constraint t_nutzer
references ProduktZahlungFENutzer(ID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Please help

You have established a reference
FHAngehörigeID INT NOT NULL IDENTITY(1,1) PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
This means that you need a record in your table FENutzer.FENutzerID that match FHAngehörigeID, in this case you cannot use IDENTITY

Your construction makes no sense - this way, you're creating two tables that depend on each other, at the primary key level - so you would have to have an existing entry in FENutzer in order to insert a new row into FHAngehörige, and this at the same time is only possible if you already have an existing row in FHAngehörige to insert the row in FEnutzer.....
You need to clean this up:
both tables need a primary key and the int identity(1,1) is a very good choice
one of the tables must reference the other, but with a normal foreign key attribute - not on the primary key.....
Since you've not given any indication as to which of the tables is the "main" table and which the "child/auxiliary" table, I'm just picking one over the other - so your table structure should be something like:
CREATE TABLE dbo.FHAngehoerige
(
FHAngehoerigeID INT NOT NULL IDENTITY(1,1)
CONSTRAINT PK_FHAngehoerige PRIMARY KEY CLUSTERED,
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE dbo.FENutzer
(
-- define the PK for the table
FENutzerID INT IDENTITY(1,1) NOT NULL
CONSTRAINT PK_FENutzer PRIMARY KEY CLUSTERED,
-- define the **foreign key** to the main table
FHAngehoerigeID INT NOT NULL
CONSTRAINT FK_FENutzer_FHAngehoerige
FOREIGN KEY REFERENCES dbo.FHAngehoerige(FHAngehoerigeID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Also: I would strongly recommend (from my own personal, bad experience) to AVOID any special characters like umlauts or accents or anything like that in table and column names.....

Related

SQL Server : foreign key references invalid table

I'm not sure what I'm doing wrong, but I'm getting a foreign key references invalid table message telling me that dbo.ValueStream is an invalid table.
Edit: I originally posted my code in the incorrect order. Fixed in the edit to reflect the order it was done in SSMS
CREATE TABLE dbo.ValueStream
(
ValueStreamKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_ValueStream_ValueStreamKey PRIMARY KEY,
ValueStream nvarchar(20),
)
CREATE TABLE dbo.NonConformance
(
NonConformanceKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_NonConformance_NonConformanceKey PRIMARY KEY,
CustomerVendorKey int NOT NULL
CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey),
ValueStreamKey int NOT NULL
CONSTRAINT FK_NonConformance_ValueStream_Key_ValueStream_ValueStreamKey
FOREIGN KEY REFERENCES dbo.ValueStream(ValueStreamKey),
RepairOrder nvarchar(50) NOT NULL,
WorkOrder nvarchar(8) NOT NULL,
PartNumber nvarchar(50) NOT NULL,
SerialNumber nvarchar(50) NOT NULL,
PartDescription nvarchar(50) NOT NULL,
InductionDate datetime NOT NULL,
TriageStartDate datetime NOT NULL,
TriageCompletionDate datetime NOT NULL,
RequiresRRCA Bit NOT NULL,
NonConformanceSummary nvarchar(max) NOT NULL
);
taking out the CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey)
(we don't have that one)
and running the scripts seperately - first the first table and then the creation of the referencing table - this works for me.
No code errors.
You are creating dbo.NonConformance first in the script that you have posted. You need to move the CREATE TABLE dbo.ValueStream statement so that it is created first, ensuring there is a GO statement still between the two CREATE TABLE statements.
As it stands you are trying to create a foreign key to a table that does not exist.

Enforce 1:0..1 relationship with EF6 Database First

In my model, I have three tables, Storage, Haul and StoragePlace. One storage can either be a place or haul. For the StoragePlace, I already achieved a 1:0..1 relationship. The problem is the Haul entity.
CREATE TABLE dbo.Haul
(
ID INT NOT NULL PRIMARY KEY IDENTITY,
ID_Storage INT NOT NULL UNIQUE,
Arrival DATETIME NOT NULL DEFAULT getdate(),
Depature DATETIME NULL,
CONSTRAINT FK_Haul_to_Storage FOREIGN KEY (ID_Storage) REFERENCES Storage(ID) ON DELETE CASCADE
)
GO
/** --- See edit below --
CREATE UNIQUE NONCLUSTERED INDEX UQX_Storage
ON Haul(ID_Storage)
WHERE ID_Storage IS NOT NULL;
GO
**/
--------------------------------------------------
CREATE TABLE dbo.Storage
(
ID INT NOT NULL PRIMARY KEY IDENTITY,
Description1 NVARCHAR(100) NULL,
Description2 NVARCHAR(100) NULL,
AddedBy NVARCHAR(50) NOT NULL
)
--------------------------------------------------
CREATE TABLE dbo.StoragePlace
(
ID INT NOT NULL PRIMARY KEY,
ID_PlantArea INT NOT NULL,
CONSTRAINT FK_StoragePlace_to_Storage FOREIGN KEY (ID) REFERENCES Storage(ID) ON DELETE CASCADE,
CONSTRAINT FK_StoragePlace_to_PlantArea FOREIGN KEY (ID_PlantArea) REFERENCES PlantArea(ID) ON DELETE CASCADE
)
My thought was, that UQX_Storage would trigger EF6 to accept a 1:0..1 relationship between Haul and Storage. Certainly, this doesn't work; it still insists on a 1:* relationship, which, from my understanding, shall not be possible with this model above.
How can I enforce the intended 1:0..1 relationship between Haul and Storage?
EDIT:
I just realized, that the ID_Storage field can never be NULL, so I replaced the UQX_Storage "constraint" with a simple ID_Storage INT NOT NULL UNIQUE,. However, that didn't solve the problem either.

SQL Server : two foreign keys pointing to one table. Error: Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

I'm getting the error:
Msg 1785, Level 16, State 0, Line 238
Introducing FOREIGN KEY constraint 'FK_Studios_Members_HeadId' on table 'Studios' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Below is a simplified version of the two tables I'm having problems with:
CREATE TABLE [Members]
(
[MemberId] int NOT NULL IDENTITY
)
CREATE TABLE [Studios]
(
[StudioId] int NOT NULL IDENTITY,
[HeadId] int,
[OwnerId] int,
CONSTRAINT [PK_Studios] PRIMARY KEY ([StudioId]),
CONSTRAINT [FK_Studios_Members_OwnerId]
FOREIGN KEY ([OwnerId]) REFERENCES [Members] ([MemberId])
ON DELETE SET NULL,
CONSTRAINT [FK_Studios_Members_HeadId]
FOREIGN KEY ([HeadId]) REFERENCES [Members] ([MemberId])
ON DELETE SET NULL
)
I found that if I switch the order of the two FK's, it will always error on the second one. I don't see why this will cause a cascading problem since both have the "ON DELETE SET NULL".
This is being generated by EF Core code-first, so I need the relationships and can't just hack in trigger in the backend.
What am I missing?
I'm not sure of an answer that will work with what you have there and I'm not sure how set in stone your design is...but as an alternate design that I don't think would have the same issue have you considered a separate middle relationship table?
One benefit of this approach is it allows you to have multiple members at each position.
CREATE TABLE [Members]
(
[MemberId] int NOT NULL IDENTITY
)
CREATE TABLE [Studios]
(
[StudioId] int NOT NULL IDENTITY,
CONSTRAINT [PK_Studios] PRIMARY KEY ([StudioId]),
)
--Contains Owner, Head, etc.
CREATE TABLE [Relationships]
(
[RelationshipId] int NOT NULL IDENTITY,
[RelationshipId] nvarchar(20) NOT NULL
)
CREATE TABLE [StudioMemberRelationships]
(
[StudioMemberRelationshipId] int NOT NULL IDENTITY,
[StudioId] int NOT NULL,
[MemberId] int NOT NULL,
[RelationshipTypeId] int NOT NULL,
CONSTRAINT [FK_StudioMemberRelationships_StudioId]
FOREIGN KEY ([StudioId]) REFERENCES [Studios] ([StudioId])
ON DELETE SET NULL,
CONSTRAINT [FK_StudioMemberRelationships_MemberId]
FOREIGN KEY ([MemberId]) REFERENCES [Members] ([MemberId])
ON DELETE SET NULL,
CONSTRAINT [FK_StudioMemberRelationships_RelationshipId]
FOREIGN KEY ([RelationshipId]) REFERENCES [Relationships] ([RelationshipId])
ON DELETE SET NULL
)

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)

Foreign key to part of primary key's table

I have a database with this tables Conversion and Client I want to create relation between this tables so ID_Send in Conversion Reference to ID in Client and ID_Receive in Conversion Reference to ID in Client
create table Conversion(ID_Send int ,
ID_Receive int ,
[Time] datetime,
[Message] varchar(2048),
primary key(ID_Send,ID_Receive,[Time])
)
create table Client (ID int IDENTITY(1,1) primary key,
[First name] varchar(500) not null,
[Last Name]varchar(500) not null,
[Birth day] datetime,
Gender bit not null,
Country varchar(200)not null,
City varchar(200) ,
[Language] varchar(200)not null,
[Chat name] varchar(500)not null ,
[Password] varchar (500)not null,
--foreign key(ID) REFERENCES Conversion (ID_Send)--there is an error
)
Motazz, there can be only one Primary key in a table like you have in the Client table. to get rid of the error:
1st create the Client table,
2nd replace the code for Conversion with:
create table Conversion(ID_Send int FOREIGN KEY REFERENCES Client(ID),
ID_Receive int FOREIGN KEY REFERENCES Client(ID),
[Time] datetime,
[Message] varchar(2048),
primary key(ID_Send,ID_Receive,[Time])
)
If you have a compound primary key (made up of mulitple columns), all your foreign keys also must use all columns of the PK to reference that table.
After all : how else would you be able to make a clear, deterministic reference from a child table to the parent? Only if you use the columns that uniquely identify one row in the parent table does this work.
The only workaround would be to put a UNIQUE index on the ID_Send and ID_Receive columns in your parent table and then reference that unique index.
But then the question is: if those values are unique - why isn't one of those columns alone your primary key??

Resources