Related
These are the tables I already have:
CREATE TABLE Gyartok
(
GyID INT IDENTITY(2, 3),
Nev VARCHAR(20),
CONSTRAINT PK_Gyartok PRIMARY KEY (GyID)
)
CREATE TABLE Focicsuka
(
CsID INT IDENTITY(2, 2),
Meret INT,
CONSTRAINT PK_Focicsuka PRIMARY KEY (CsID)
)
CREATE TABLE FcsGyartjaGya
(
GyID INT IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1
FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2
FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya
PRIMARY KEY (GyID, CsID)
)
The problem is that every time I try to add new values to the table (like such)
INSERT INTO FcsGyartjaGya (Ar) VALUES (300);
I get an error saying I didn't initialize the CsID INT column:
Cannot insert the value NULL into column 'CsID', table 'Lab3.dbo.FcsGyartjaGya'; column does not allow nulls. INSERT fails.
I know I must initialize it with something, but I have no idea what do to it with, because IDENTITY(x, y) doesn't work (it's occupied by another column already) and adding another parameter to the code (like such)
INSERT INTO FcsGyartjaGya (Ar, CsID) VALUES (300, 7);
creates another error which says
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Lab3a", table "dbo.Gyartok", column 'GyID'.
It is important to note that I already filled every column with data, so that couldn't be the problem.
As I mention in the comments, your INSERT will work fine, provided the stars align correctly. For your table Gyartok you have GyID as your PRIMARY KEY, which is defined as a IDENTITY(2,3); so the first value generated is 2 and then each row attempted to be INSERTed will increment by 3.
So, if we run the following, we get the IDs 2, 5, 7 and 17. (11 and 14 are skipped as the INSERT failed).
CREATE TABLE Gyartok (
GyID INT IDENTITY(2, 3),
Nev VARCHAR(20),
CONSTRAINT PK_Gyartok PRIMARY KEY (GyID)
);
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES ('asdfjahsbvd'),
('ashjkgdfakd'),
('kldfbhjo');
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES (REPLICATE('A',25)), --Force a truncation error
('ashjkgdfakd');
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES (REPLICATE('A',15));
Let's now add some data for your other table:
CREATE TABLE Focicsuka (
CsID INT IDENTITY(2, 2),
Meret INT,
CONSTRAINT PK_Focicsuka PRIMARY KEY (CsID)
)
INSERT INTO dbo.Focicsuka (Meret)
VALUES(12),
(25);
Now we want to INSERT into the table FcsGyartjaGya, defined as the following:
CREATE TABLE FcsGyartjaGya (
GyID INT IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1 FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2 FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya PRIMARY KEY (GyID, CsID)
)
This has a IDENTITY on GyID, but defined as an IDENTITY(3,2), so the first value is 3 and then incremented by 2.
As this has 2 foreign keys, on GyID and CsID when we INSERT the row the values must appear in the respective tables. As GyID is defined as anIDENTITY(3,2) however, this is where we need to rely on the Stars luck for the INSERT to work. Why? Well 2 + (3*n) and 3+(2*n) can give very different numbers. The first are as you saw at the start of this answer. For the latter, we have numbers like 3, 5, 7, 9, 11. As you can see, only 1 in 3 of these numbers match a number in our original sequence, so luck is what we are going to be relying on.
Let's, therefore, try a single INSERT.
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(2,1);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Sandbox", table "dbo.Gyartok", column 'GyID'.
Well, that didn't work, but it was expected. 3 isn't a value in the table Gyartok. Let's try again!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(2,2);
It worked! The stars Luck was our side, and the IDENTITY value was a value in the table Gyartok. Let's try a couple of rows this time!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,3),
(4,4);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Sandbox", table "dbo.Gyartok", column 'GyID'.
No!! Not again. :( That's because the stars didn't align; 7 and 9 aren't in the other table. But wait, 11 was in the sequence, so let's try that:
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,5);
Error, again?! No, it cannot be!!! :( Oh wait, I forgot, the stars were against us before, because that INSERT failed against Gyartok for the value of 11. I need to wait for 17!
--13 fails
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
GO
--15 fails
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
GO
--17 works!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
And now we have another row in our table.
So what is the problem? Your design. GyID is defined as an IDENTITY and a FOREIGN KEY; meaning you are at the "whims" of SQL Server generating a value valid. This is not what you want. Just don't define the column as an IDENTITY and then INSERT the data with all 3 of your columns defined:
CREATE TABLE FcsGyartjaGya (
GyID int,-- IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1 FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2 FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya PRIMARY KEY (GyID, CsID)
)
GO
INSERT INTO dbo.FcsGyartjaGya (GyID, CsID, Ar)
VALUES(2,2,1),
(2,4,2),
(5,4,3),
(8,2,4),
(8,4,5);
And all these rows insert fine.
I think there is a bit confusion, if I understand correctly what You're trying to do, then you have two tables each with their own id, which is based on an identity column, so you get new values in those for free.
Then you are trying to make a relation table with extra data.
Issue 1: You cannot have FcsGyartjaGya.GyID be identity if it refers to Gyartok.GyID because you will want to insert into it and not rely on an auto increment. If it doesn't refer to the same it should have another name or my head will possibly explode :))
Issue 2: When populating a relation table you need to insert it with what pairs you want, there is no way SQL server can know how it should match these identity pairs in the relation table
I think this is what people are aiming at in the comments, for example
to insert a relationship between row with Focicsuka.CsID = 1 to Gyartok.GyID 7 and adding Ar = 300 have to look like
INSERT INTO FCSGYARTJAGYA(GYID, CSID, AR)
VALUES(7, 1, 300)
Unless You've forgotten to mention that you want to put some value for each of some value or based on something which can be scripted, in other words unless You have logics to define the pairs and their values, relationship tables cannot have defaults on their foreign key fields.
I have a SQL script but there is an issue with the order of the statements in the script
e.g.
INSERT INTO PERMISSIONS_FOR_ROLE (ROLE_ID, PERMISSION_ID) VALUES (3, 8);
INSERT INTO permissions (id, name) VALUES (8, 'update');
The order of occurrence in the script should have been reverse! And this results in a error because the foreign key with id 8 is not yet inserted when the first statement executes
leading to:
[Code: -177, SQL State: 23503] integrity constraint violation:
foreign key no parent; PERMISSIONS_FOR_ROLE_PERM_FK table: PERMISSIONS_FOR_ROLE value: 8
statements used to create the relationships are as below
create table PERMISSIONS ( ID bigint not null, NAME varchar(255), primary key (ID) );
create table PERMISSIONS_FOR_ROLE ( ROLE_ID bigint not null, PERMISSION_ID bigint not null, primary key (ROLE_ID, PERMISSION_ID) );
alter table PERMISSIONS_FOR_ROLE add constraint permissions_for_role_perm_fk foreign key (PERMISSION_ID) references PERMISSIONS;
Any suggestions on how to execute such a script ? I tried manually changing the order and the script executes properly but is there any other way to do it as its run as part of a ANT build target.
For mass inserts with very large scripts that are out of order, you can disable referential integrity checks with:
SET DATABASE REFERENTIAL INTEGRITY FALSE
see http://hsqldb.org/doc/2.0/guide/management-chapt.html#mtc_sql_settings on how to check for possible violations after the insert.
I'm trying to set my sql scripts into a transaction to achieve atomicity with my database.
The table structure is (simplified):
CREATE TABLE foo (
id serial NOT NULL,
foo varchar(50) NOT NULL,
CONSTRAINT foo_pk PRIMARY KEY (id)
);
CREATE TABLE access (
id serial NOT NULL,
foo_id int NULL
CONSTRAINT access_pk PRIMARY KEY (id)
);
ALTER TABLE access ADD CONSTRAINT access_foo
FOREIGN KEY (foo_id)
REFERENCES foo (id)
ON DELETE CASCADE
ON UPDATE CASCADE
DEFERRABLE
INITIALLY DEFERRED;
In my code I first declare:
client.query('BEGIN'); (I'm using npm library 'pg') then
insert a row into a table 'foo', then another insert to 'access' with a foo_id from the first insert. After that there is client.query('COMMIT');
All of this is in a try catch, and in the catch is client.query('ROLLBACK'); and the rolling back seems to be working if there is an issue either of the inserts. When everything should be committed I still end up in the catch block for this:
message: "insert or update on table "access" violates foreign key constraint "access_foo""
detail: "Key (foo_id)=(20) is not present in table "foo"."
I thought that deferring constraint would be enough to do this, but I guess I'm wrong. Any help is welcome.
You probably have some issue with the transaction demarcation. I ran a simple test and works wells.
insert into foo (id, foo) values (1, 'Anne');
start transaction;
insert into access (id, foo_id) values (101, 1);
insert into access (id, foo_id) values (107, 7); -- 7 does not exist yet...
insert into foo (id, foo) values (7, 'Ivan'); -- 7 now exists!
commit; -- at this point all is good
See running example at DB Fiddle.
As you can see in the code. three table have its own primary key. "protectmedalno" and "mastermedalno" are the foreign key of the player table.
protectmedalno could not be null. masterdealno could be null. I drop table protector first, then drop master , the last drop player.
There is weak relationship between table player and table master.
There is no problem with inserting the value of protector and master.
But inserting the value into table player, it will occur:
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
I think that it is a problem with constraint.
insert into player values('01','Joe','101','');
insert into player values('02','Elsa','102','201');
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy')
commits;
It could display the protector table and the master table.
But it could not show the player table.
drop table protector;
drop table master;
drop table player;
CREATE TABLE player (
playno NUMBER(2) NOT NULL,
playname VARCHAR2(30) NOT NULL,
protectmedalno CHAR(10) NOT NULL,
mastermedalno CHAR(10)
);
ALTER TABLE player ADD CONSTRAINT play_pk PRIMARY KEY ( playno );
CREATE TABLE protector (
protectmedalno CHAR(3) NOT NULL,
protectname VARCHAR2(30) NOT NULL
);
ALTER TABLE protector ADD CONSTRAINT protector_pk PRIMARY KEY ( protectmedalno );
CREATE TABLE master (
mastermedalno CHAR(3) NOT NULL,
mastername VARCHAR2(30) NOT NULL
);
ALTER TABLE master ADD CONSTRAINT master_pk PRIMARY KEY ( mastermedalno );
ALTER TABLE player
ADD CONSTRAINT player_protector_fk FOREIGN KEY ( protectmedalno )
REFERENCES protector ( protectmedalno );
ALTER TABLE player
ADD CONSTRAINT player_master_fk FOREIGN KEY ( mastermedalno )
REFERENCES master ( mastermedalno );
Since protector and master are the primary tables, you should populate the records there first. Then, insert into player and refer to those records:
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy');
insert into player values('01','Joe','101','201'); -- refer to master
insert into player values('02','Elsa','102','201'); -- refer to master
Note that I edited the inserts into the player table such that both records refer to a record in the master table which actually exists.
You first have to insert protector and master, afterwards insert player since player refers to master and protector and values have to be inside there.
Do otherwise round on delete...
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy');
insert into player values('01','Joe','101','');
insert into player values('02','Elsa','102','201');
If you delete first delete from player, then from protector and master.
To insert data in the player table, you need a record in the protector table. This is because of the foreign key restriction.
When inserting data in a table that has a foreign key(Which in this case of protector vs player, cannot be null), you have to create the foreign record first.
1. insert into protector values('101','Dragon');
2. insert into player values('01','Joe','101','');
3. insert into protector values('102','Lion');
4. insert into master values('201','Fairy');
5. insert into player values('02','Elsa','102','201');
commits;
I hope this helps, happy debugging :)
You are inserting in the wrong order: you must insert the master and protector first so that when you insert the player it can reference them:
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy');
insert into player values('01','Joe','101',NULL);
insert into player values('02','Elsa','102','201');
Edit: '' is not NULL it's an empty String. To insert null use the explicit NULL jeyword.
Always include the columns when doing an insert. You should also use single quotes for only string and date constants.
insert into player(playno, playname, protectmedalno, mastermedalno)
values(1, 'Joe', '101', '');
I don't think the problem is specifically on player, but you should do this for all your inserts and you'll find the problem.
Populating the "parent" tables first (as our colleagues have suggested) is a step towards solving the problem. In order to get the foreign key constraint to work properly, I suggest modifying the DDL code, too.
With your tables in place (using Oracle 12c), we can do the following:
begin
insert into master ( mastermedalno, mastername ) values ('201','Fairy') ;
insert into protector ( protectmedalno, protectname )
values( '101', 'Dragon');
insert into protector ( protectmedalno, protectname )
values( '102', 'Lion');
end ;
/
SQL> select * from master;
MAS MASTERNAME
--- ------------------------------
201 Fairy
SQL> select * from protector ;
PRO PROTECTNAME
--- ------------------------------
101 Dragon
102 Lion
So far so good. When INSERTing into PLAYER, we get:
insert into player ( playno, playname, protectmedalno, mastermedalno )
values('02', 'Elsa', '102', '201');
-- ORA-02291: integrity constraint (...PLAYER_MASTER_FK) violated - parent key not found
Suggestion: use the same datatype for the foreign key and the referenced key. Just drop the PLAYER table (including its constraints), and create it afresh:
drop table player cascade constraints ;
CREATE TABLE player (
playno NUMBER(2) NOT NULL,
playname VARCHAR2(30) NOT NULL,
protectmedalno CHAR(3) NOT NULL, -- changed (was: CHAR(10))
mastermedalno CHAR(3) -- changed (was: CHAR(10))
);
ALTER TABLE player
ADD CONSTRAINT player_protector_fk FOREIGN KEY ( protectmedalno )
REFERENCES protector ( protectmedalno );
ALTER TABLE player
ADD CONSTRAINT player_master_fk FOREIGN KEY ( mastermedalno )
REFERENCES master ( mastermedalno );
Now execute the INSERTs.
begin
insert into player values('01','Joe','101',''); -- original INSERT
insert into player values('02','Elsa','102','201'); -- original INSERT
commit;
end;
/
-- PL/SQL procedure successfully completed.
The tables contain the following data now:
SQL> select * from player ;
PLAYNO PLAYNAME PROTECTMEDALNO MASTERMEDALNO
1 Joe 101 NULL
2 Elsa 102 201
SQL> select * from master ;
MASTERMEDALNO MASTERNAME
201 Fairy
SQL> select * from protector;
PROTECTMEDALNO PROTECTNAME
101 Dragon
102 Lion
Are both foreign key constraints working now? Yes.
SQL> insert into player values('03','Fifi','101','202');
Error starting at line : 1 in command -
insert into player values('03','Fifi','101','202')
Error report -
ORA-02291: integrity constraint (...PLAYER_MASTER_FK) violated - parent key not found
SQL> insert into player values('03','Fifi','103','201');
Error starting at line : 1 in command -
insert into player values('03','Fifi','103','201')
Error report -
ORA-02291: integrity constraint (...PLAYER_PROTECTOR_FK) violated - parent key not found
In SQL Server 2012 Management studio, I tried many time to create some tables and insert into the tables some values, but the problem here is in relationship with tables :
The INSERT statement conflicted with the FOREIGN KEY constraint
The Errors :
Msg 8152, Level 16, State 14, Line 116 String or binary data would be
truncated.
Msg 547, Level 16, State 0, Line 122 The INSERT statement conflicted
with the FOREIGN KEY constraint "eworkerFK". The conflict occurred in
database "7", table "dbo.member_clup", column 'manager_id'.
The statement has been terminated.
Msg 547, Level 16, State 0, Line 128
The INSERT statement conflicted with the FOREIGN KEY constraint
"SALEDFk". The conflict occurred in database "7", table "dbo.worker",
column 'worker_number'.
Can anyone help me to insert values into the correct
tables ?
CREATE TABLE address
(
code_place int,
PLACE_NAME VARCHAR (15),
OUT_israel varchar (15)
CONSTRAINT address1 PRIMARY KEY(code_place)
)
create table member_clup
(
manager_id int,
manager_name varchar(15),
manager_last varchar(12),
phone_num int,
type varchar(10),
CONSTRAINT manager1PK PRIMARY KEY(manager_id)
)
create table worker
(
worker_number int,
worker_name varchar(50),
worker_last varchar(49),
id varchar(9),
type varchar(50),
manager_id int
CONSTRAINT workerPK PRIMARY KEY(worker_number)
CONSTRAINT eworkerFK FOREIGN KEY(manager_id)
REFERENCES member_clup(manager_id)
)
CREATE TABLE rooms(
room_number int,
floor int,
room_type varchar(8)
CONSTRAINT roomsKEY PRIMARY KEY(room_number)
)
CREATE TABLE cars
(
cars_number int,
car_type varchar(15),
car_model int,
CONSTRAINT carsPK PRIMARY KEY(cars_number)
)
CREATE TABLE tourest(
Cust_number int ,
Cust_name varchar(50),
cust_lastname varchar(50),
cust_phone varchar(10),
code_place int,
Room_id int,
Saledby int
CONSTRAINT tourest1 PRIMARY KEY(Cust_number)
CONSTRAINT addressFK FOREIGN KEY(code_place)
REFERENCES address(code_place),
CONSTRAINT SALEDFk FOREIGN KEY(Saledby)
REFERENCES worker(worker_number),
CONSTRAINT roomsFK FOREIGN KEY(Room_id)
REFERENCES rooms(room_number)
)
CREATE TABLE kesher
(
Cust_number int,
cars_number int,
CONSTRAINT custPK1 PRIMARY KEY(Cust_number,cars_number),
CONSTRAINT kesher1FK FOREIGN KEY(Cust_number)
REFERENCES cars(cars_number),
CONSTRAINT kesherFK FOREIGN KEY(Cust_number)
REFERENCES tourest(Cust_number)
)
insert into cars VALUES
(100100,'mazda',2002),
(100205,'ford',2017),
(100206,'porch',1998),
(100207,'mazda',2017),
(100208,'opel',2002),
(100209,'mazda',2016),
(100210,'pijuot',2002),
(100211,'mazda',2015),
(100212,'mazda',2010),
(100213,'volvo',2002),
(100215,'ford',20012)
insert into rooms VALUES
(100,1,'single'),
(101,1,'double'),
(102,1,'single'),
(103,1,'double'),
(201,2,'signle'),
(202,2,'signle'),
(203,2,'signle'),
(204,2,'signle'),
(300,3,'double'),
(301,3,'double'),
(302,3,'double'),
(303,3,'double'),
(304,3,'signle')
insert into address VALUES
(500,'Akko','no'),
(501,'Haifa','no'),
(502,'Nahariya','no'),
(503,'Nataniya','no'),
(504,'carmieal','no'),
(505,'Nahef','no'),
(507,'Nitsrat','no'),
(510,'OUT','yes')
insert into member_clup VALUES
(5400,'shmolek','snaa','0525732572','General'),
(5696,'malloc','ali','0525552501','Rooms'),
(5991,'ramada','hassan','0532731212','Rooms & Tips'),
(5210,'meri','yako','0525022572','General Manager')
insert into worker
VALUES(1234,'halaa','khaled',1234567,'none',5696),
(2234,'fares','adoon',6542897,'none',5696),
(6670,'halaa','khaled',1001234,'none',5991),
(2554,'halaa','khaled',5658741,'none',5210),
(9987,'halaa','khaled',1123456,'none',5400)
insert into tourest VALUES
(1510,'moshe','yke','0525732579',500,101,2234),
(1520,'ninar','lait','052655541',500,102,6670),
(1521,'hasan','ahmad','0532578741',501,101,2234),
(1522,'ameer','karm','0545222741',500,104,6670),
(1523,'aliel','sraa','0525771572',504,100,2234),
(1524,'hasa','veto','0525122579',505,303,6670),
(1525,'saed','snaa','05255632579',505,303,2234),
(1526,'yakov','mero','0528132579',502,202,6670),
(1527,'mece','loka','0525962579',502,302,9987),
(1528,'ana','yokaf','0525791179',502,302,9987),
(1529,'lelya','mandlina','0527832579',505,203,9987),
(1530,'mnal','khokha','0525758579',507,204,5991),
(1531,'moka','panana','0525805579',507,200,2234)
insert into kesher VALUES
(1510,100100),
(1520,100209),
(1521,100100),
(1522,100209),
(1523,100206),
(1524,100206),
(1525,100213),
(1526,100206),
(1527,100213),
(1528,100213),
(1529,100209)
This code is straightforward to debug, you surely can work it out. Run each statement on it's own and see its result. If it fails, split it into smaller statements and repeat. If you can't split it, it's already small enough to debug by eyesight, it won't take long to figure the issue.
Before debugging though, know this, restarting from scratch is sometimes helpful/necessary, so have restart script(s) ready. In this scenario only a bunch of DROP TABLEs are necessary, they'll remove the tables and their records.
Your CREATE TABLE statements are working fine, that's one thing passed. Even if you had problems with them though, run them one by one to debug, not all at once.
Your INSERTs are problematic, yeah. Run each INSERT block one by one, and for the block that fails, split it into individual INSERT statements, one per record, and now you'll be able to tell which row is the problem.
Even though you cite certain foreign key conflict issues, I'm getting a bunch of different foreign key issues. Double-check the code you provided. Also,
the order of what statement is ran first matters (can I furnish the third floor of my house while I don't even have third and second floors? Can you cancel a booking that you didn't book yet?)
Lastly, the data seem to have truncation issues, whether the table column should be bigger or the records' values are incorrect is something only you can tell.