SQL deleting connected rows and adding same values - sql

Alright, so I managed to connect these two tables:
CREATE TABLE [dbo].[T_Artikli] (
[ArtikliId] INT IDENTITY (1, 1) NOT NULL,
[Naziv] NVARCHAR (100) NOT NULL,
[Sifra] VARCHAR (13) NOT NULL,
[Vp] FLOAT (53) NOT NULL,
[MP] FLOAT (53) NOT NULL,
[Napomena] NVARCHAR (300) NOT NULL,
PRIMARY KEY CLUSTERED ([ArtikliId] ASC)
);
and
CREATE TABLE [dbo].[T_Stanje] (
[StanjeId] INT IDENTITY (1, 1) NOT NULL,
[Trenutno] INT NOT NULL,
[Naruceno] INT NOT NULL,
[Datum] DATE NOT NULL,
[Firma] NVARCHAR (40) NOT NULL,
[ArtiklId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([StanjeId] ASC),
CONSTRAINT [FK_T_Stanje_T_Artikli] FOREIGN KEY ([StanjeId]) REFERENCES [dbo].[T_Artikli] ([ArtikliId])
);
And it works like a charm. When it comes to deleting one of these tables rows I did it simple like this:
When deleting Artikl table (ArtiklId and ArtikliId is not a typo :D )
string deleteSql =
"DELETE FROM T_Stanje WHERE ArtiklId = #Id " +
"DELETE FROM T_Artikli WHERE ArtikliId = #Id;";
and when deleting Stanje table
string deleteSql =
"DELETE FROM T_Stanje WHERE StanjeId = #Id;";
These also work like a charm BUT when I add values to Artikli and Stanje and then deleting that Stanje row I am unable to add NEW Stanje for that same Artikli.

First of all, you are using identity which is automatically generated. so you cannot create the same row.
Secondly, you referenced the wrong foreign key I believe

The problem is here
CONSTRAINT [FK_T_Stanje_T_Artikli]
FOREIGN KEY ([StanjeId])
REFERENCES [dbo].[T_Artikli] ([ArtikliId])
Your foreign key is incorrect. It should be:
CONSTRAINT [FK_T_Stanje_T_Artikli]
FOREIGN KEY ([ArtiklId])
REFERENCES [dbo].[T_Artikli] ([ArtikliId])

I think
CONSTRAINT [FK_T_Stanje_T_Artikli]
FOREIGN KEY ([StanjeId])
REFERENCES [dbo].[T_Artikli] ([ArtikliId])
should be
CONSTRAINT [FK_T_Stanje_T_Artikli]
FOREIGN KEY ([ArtiklId])
REFERENCES [dbo].[T_Artikli] ([ArtikliId])

Related

No primary or candidate keys in the referenced table?

I keep getting an error:
There are no primary or candidate keys in the referenced table 'TProducts' that match the referencing column list in the foreign key 'TProducts_TCategories_FK'."
When trying to establish a relationship between my products table and categories table. I have checked the spelling multiple times but can't seem to figure out why I keep getting this error. The rest of my tables are fine, and I used the same method.
CREATE TABLE TCategories
(
intCategoryID INTEGER NOT NULL,
strCategoryName VARCHAR(255) NOT NULL,
CONSTRAINT TCategories_PK PRIMARY KEY (intCategoryID)
)
CREATE TABLE TProducts
(
intProductID INTEGER NOT NULL,
intVendorID INTEGER NOT NULL,
intCategoryID INTEGER NOT NULL,
strProductName VARCHAR(255) NOT NULL,
monCostofProduct MONEY NOT NULL,
monRetailCost MONEY NOT NULL,
intInventory INTEGER NOT NULL,
CONSTRAINT TProducts_PK PRIMARY KEY (intProductID)
)
ALTER TABLE TProducts
ADD CONSTRAINT TProducts_TCategories_FK
FOREIGN KEY (intCategoryID) REFERENCES TProducts (intCategoryID)
You are referencing to TProducts table and not TCategories table:
ALTER TABLE TProducts ADD CONSTRAINT TProducts_TCategories_FK
FOREIGN KEY ( intCategoryID ) REFERENCES TCategories( intCategoryID )

Referenced table not found in the data dictionary mariadb

so I have written this Mariadb code as the solution for an assignment and am running it on HeidiSQL. It should work in theory however I am getting the error message SQL Error (1005): Can't create table bestellung.arbeitetin (errno: 150 "Foreign key constraint is incorrectly formed"). Upon using show warning, the program elaborates that "referenced table bestellung.arbeitetin not found in the data dictionary". I am wondering, is there something wrong with the code?
Datum date not NULL,
Abholtermin DATE,
Kostenstelle int not NULL,
Abteilung char(5) not NULL,
Mitarbeiter int not NULL,
Telefon int not NULL,
primary key (Bestellnummer)
);
create table enthaelt (
FK_Bestellnummer int not NULL,
FK_Artikelnummer char(10) not NULL,
Menge int not NULL,
unique key (FK_Bestellnummer, FK_Artikelnummer)
);
alter table enthaelt ADD
constraint FK_ArtikelNr
foreign key (FK_Artikelnummer)
references Artikel (Artikelnummer);
alter table enthaelt ADD
constraint FK_BestellNr
foreign key (FK_Bestellnummer)
references Bestellung (Bestellnummer);
create table arbeitetin
(
FK_PersNr int not NULL,
FK_ProjektNr int not NULL,
unique key(FK_PersNr, FK_ProjektNr)
);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_MITARBEITER1
FOREIGN KEY (FK_PersNr)
REFERENCES Mitarbeiter (PersNr);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_PROJEKT
foreign key (FK_ProjektNr)
references Projekt (ProjektNr);
alter table Mitarbeiter ADD
constraint FK_MITARBEITER_ABTEILUNG
foreign key (FK_Abkuerzung)
references Abteilung (Abkuerzung); ```

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' 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.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);

SQL Syntax error with foreign keys

now i have table place CREATE TABLE [dbo].[Place] (
[Place_Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Building_Date] DATE NULL,
[Longitude] VARCHAR (50) NULL,
[Latitude] VARCHAR (50) NULL,
[Location] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Place_Id] ASC)
); , and table Citeria CREATE TABLE [dbo].[Criteria] (
[Criteria] VARCHAR (50) NOT NULL,
[Place_Id] INT NOT NULL, PRIMARY KEY CLUSTERED ([Criteria], [Place_Id]), CONSTRAINT [FK_Criteria_ToTable] FOREIGN KEY (Place_Id) REFERENCES Place(Place_Id)
);and The referenced table '[dbo].[Criteria]' 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.
.
The error is correct. Subqueries are not allowed in check constraints.
But, you already have a foreign key reference between user_name and likes(user_name), so this condition is already in place. The only thing is would really be checking is that user_name is not NULL, but that is already true by the definition of the column.
Now, there are other issues. Your foreign keys should be to primary keys or unique keys in other tables. I think this is your intention:
CREATE TABLE [dbo].Normal_Upload
(
[User_Name] VARCHAR(50) NOT NULL ,
[Place_Id] INT NOT NULL,
[Image] IMAGE NOT NULL,
CONSTRAINT [FK_Normal_Upload] FOREIGN KEY (User_Name) REFERENCES Member(User_Name),
CONSTRAINT [FK_Normal_Upload_1] FOREIGN KEY (Place_Id) REFERENCES Place(Place_Id),
CONSTRAINT [FK_Normal_Upload_2] FOREIGN KEY (User_Name, Place_Id) REFERENCES Likes(User_Name, Place_Id)
);
As a note on naming. I think the primary keys of tables should include the table name. So, consider Member_Name rather than User_Name for the Member table.
It wrong db design, never use varchar or character type column in reference key or primary-key(try to avoid as much as possible).
For you solution, create a column "useid" with int datatype and give pk to it. and update the following table
CREATE TABLE [dbo].[Likes] (
[User_id] VARCHAR (50) Identity (1,1),
[User_Name] VARCHAR (50) NOT NULL,
[Place_Id] INT NOT NULL,
CONSTRAINT [PK_Likes] PRIMARY KEY CLUSTERED ([User_id] ASC, [Place_Id] ASC),
CONSTRAINT [FK_Likes_ToTable] FOREIGN KEY ([User_Name]) REFERENCES Normal ([User_Name]),
CONSTRAINT [FK_Likes_ToTable_1] FOREIGN KEY ([Place_Id]) REFERENCES [dbo].[Place] ([Place_Id]),
);

Error Defining Foreign Key

I have the following two database tables defined:
CREATE TABLE [dbo].[Classrooms] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[ClassroomName] VARCHAR (30) NOT NULL,
CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [FK_Classrooms_SystemAccount] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [dbo].[SystemAccounts] ([ID])
);
CREATE TABLE [dbo].[Students] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[Classroom_ID] INT NULL,
[PhotoID] INT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (40) NOT NULL,
[NewsTemplate] TINYINT NOT NULL,
CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Students_Classrooms] FOREIGN KEY ([Classroom_ID]) REFERENCES [dbo].[Classrooms] ([ID]),
CONSTRAINT [FK_Students_SystemAccounts] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [dbo].[SystemAccounts] ([ID])
);
Data model details:
Students belong to zero or one classroom via Classroom_ID FK
Students belong to one System Account via SystemAccount_ID FK
Classrooms belong to one System Account via SystemAccount_ID FK (implying a system account can have zero or more Classrooms)
What I'm attempting to do is enforce when students are added to a classroom (by setting the Classroom_ID key in the Students table) that the classroom belongs to the same system account as the student. I could easily enforce this at the business logic layer but then I'd be requiring every programmer to remember to do this. So ideally, I'd be able to do this at the data layer as a constraint.
I tried adding a FK constraint to the Students table:
CONSTRAINT [FK_Students_ToTable] FOREIGN KEY ([SystemAccount_ID]) REFERENCES [Classrooms]([SystemAccount_ID])
Which results in the following error compliments of SQL Server:
Update cannot proceed due to validation errors.
Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[Classrooms]' 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.
I've tried a few different things but my SQL mojo isn't powerful enough to hack past this one. Any help would be greatly appreciated.
Add a UNIQUE constraint on the combination of the two columns in Classrooms:
CREATE TABLE [dbo].[Classrooms] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[ClassroomName] VARCHAR (30) NOT NULL,
CONSTRAINT [PK_Table]
PRIMARY KEY CLUSTERED ([ID]),
CONSTRAINT [FK_Classrooms_SystemAccount]
FOREIGN KEY ([SystemAccount_ID])
REFERENCES [dbo].[SystemAccounts] ([ID]),
CONSTRAINT [UQ_Classrooms_ID_SystemAccount_ID]
UNIQUE ([SystemAccount_ID], [ID])
);
Then, in the Students table, combine the two FOREIGN KEY constraints into one, or in your case (because Classroom_ID isnullable), change the FK to Classroom to use the combination of the two columns:
CREATE TABLE [dbo].[Students] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[SystemAccount_ID] INT NOT NULL,
[Classroom_ID] INT NULL,
[PhotoID] INT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (40) NOT NULL,
[NewsTemplate] TINYINT NOT NULL,
CONSTRAINT [PK_Students]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Students_Classrooms]
FOREIGN KEY ([SystemAccount_ID], [Classroom_ID])
REFERENCES [dbo].[Classrooms] ([SystemAccount_ID], [ID]),
CONSTRAINT [FK_Students_SystemAccounts] -- this wouldn't be needed if
FOREIGN KEY ([SystemAccount_ID]) -- Classrooms_ID was NOT NULL
REFERENCES [dbo].[SystemAccounts] ([ID])
);