I am trying to add one row of data into a table (Employee) that has a Foreign Key (ob_Num). Job_Num is referenced in the Job table. However, when I go to add the row I get the below error:
Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted
with the FOREIGN KEY constraint "FK__Employee__Job_Nu__5D60DB10". The
conflict occurred in database "team04", table "dbo.Job", column
'Job_Num'. The statement has been terminated.
My code is:
Insert into Employee Values (001, 'Celie', 'Davis', 457-457-4511, 002,
'01-05-2012', null);
002 is the job_num
Related
I created triggers after creating a database in oracle apex. When testing in SQL code everything was fine, they worked. In the application I have the Professors table and when I change the value of the column "name", in the Courses table the value of the column "professor_name" should change. However when I change the value of the column "name" in the Professors table it throws me the error.
Here is the trigger definition:
CREATE OR REPLACE TRIGGER profesori_upd
AFTER UPDATE OF ime on profesori
FOR EACH ROW
BEGIN
UPDATE kursevi set ime_profesora = :new.ime
where pr_jmbg= :new.jmbg_pr;
END;
Here is the table Proffesors:
CREATE TABLE PROFESORI( jmbg_pr VARCHAR2(13) PRIMARY KEY,
ime VARCHAR2(20) NOT NULL,
prezime VARCHAR2(20) NOT NULL,
id_spreme NUMBER(5) NOT NULL,
CONSTRAINT profesor_sprema_fk FOREIGN KEY (id_spreme) REFERENCES
STRUCNE_SPREME(id)
);
Here is the table Courses:
CREATE TABLE KURSEVI(
opis VARCHAR2(40),
id_jezik NUMBER(10) NOT NULL,
id_nivo NUMBER(10) NOT NULL,
pr_jmbg VARCHAR2(13) NOT NULL,
CONSTRAINT kurs_jezik_fk FOREIGN KEY (id_jezik) REFERENCES JEZICI(id_j),
CONSTRAINT kurs_nivo_fk FOREIGN KEY (id_nivo) REFERENCES NIVOI_KURSEVA(id_n),
CONSTRAINT kurs_profesor_fk FOREIGN KEY (pr_jmbg) REFERENCES PROFESORI(jmbg_pr),
CONSTRAINT kurs_pk PRIMARY KEY(id_jezik,id_nivo,pr_jmbg)
);
After denormalization I added columns ime_profesora and prezime_profesora to the table Courses:
ALTER TABLE KURSEVI
ADD ime_profesora VARCHAR2(20);
ALTER TABLE KURSEVI
ADD prezime_profesora VARCHAR2(20);
UPDATE KURSEVI SET ime_profesora=( SELECT ime FROM PROFESORI WHERE profesori.jmbg_pr=kursevi.pr_jmbg);
UPDATE KURSEVI SET prezime_profesora=( SELECT prezime FROM PROFESORI WHERE profesori.jmbg_pr=kursevi.pr_jmbg);
ALTER TABLE KURSEVI
MODIFY ime_profesora varchar2(20) not null;
ALTER TABLE KURSEVI
MODIFY prezime_profesora varchar2(20) not null;
Error occurs after I try to change the value of the column name in the application, it does not say what the error is.
I am using Django1.9 with Postgresql. This is my data model for the model "Feature" :
class Feature(models.Model):
image_component = models.ForeignKey('Image_Component',on_delete=models.CASCADE,)
feature_value = HStoreField()
def save(self,*args,**kwargs):
if Feature.objects.filter(feature_value__has_keys=['size', 'quality' , 'format']):
super(Feature, self).save(*args, **kwargs)
else:
print("Incorrect key entered")
I am imposing a restriction on the feature_value such that only the keys that is allowed with Hstore are size , format and quality. I can do this while updating the database using Django-Admin. But I am not able to update the database directly using pgAdmin3 with the same restrictions i.e , I want to impose the same restrictions on the database level. How can I do that? Any suggestions?
You need to ALTER you Future table and add a constraint for feature_value field with such query:
ALTER TABLE your_feature_table
ADD CONSTRAINT restricted_keys
CHECK (
-- Check that 'feature_value' contains all specified keys
feature_value::hstore ?& ARRAY['size', 'format', 'quality']
AND
-- and that number of keys is three
array_length(akeys(feature_value), 1) = 3
);
This will ensure that every data in feature_value could contain exactly three keys: size, format and quality; and won't allow empty data.
Note, that before applying this query, you need to remove all invalid data from the table, or you would receive an error:
ERROR: check constraint "restricted_keys" is violated by some row
You could execute this query in DB console, or since you're using Django, it would be more appropriate to create a migration and apply this query using RunSQL: create an emtpy migration and pass above query into migrations.RunSQL, and pass this query into reverse_sql param for removing the constraint when the migration is unapplied:
ALTER TABLE your_feature_table
DROP CONSTRAINT restricted_keys;
After applying:
sql> INSERT INTO your_feature_table (feature_value) VALUES ('size => 124, quality => great, format => A4')
1 row affected in 18ms
sql> INSERT INTO your_feature_table (feature_value) VALUES ('format => A4')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("format"=>"A4").
sql> INSERT INTO your_feature_table (feature_value) VALUES ('')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ().
sql> INSERT INTO your_feature_table (feature_value) VALUES ('a => 124, b => great, c => A4')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("a"=>"124", "b"=>"great", "c"=>"A4").
sql> INSERT INTO your_feature_table (feature_value) VALUES ('size => 124, quality => great, format => A4, incorrect_key => error')
ERROR: new row for relation "your_feature_table" violates check constraint "restricted_keys"
Detail: Failing row contains ("size"=>"124", "format"=>"A4", "quality"=>"great", "incorrect_ke...).
I trying to code a many to many relationship in c++ sqlite3.
in the diagram below,
managers can add many job opportunities.
jobs opportunities is being add by many managers
my create table statements
"CREATE TABLE Manager(" \
"manager_id INTEGER PRIMARY KEY NOT NULL,"\
"name varchar(45) NOT NULL);"
"CREATE TABLE jobs ("
"jobId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"\
"jobTitle varchar(45) NOT NULL);"
"CREATE TABLE Add ("
"manager_id,jobId INTEGER PRIMARY KEY NOT NULL,"\
"date varchar(45) NOT NULL,"\
"FOREIGN KEY(manager_id) REFERENCES Manager(manager_id),"\
"FOREIGN KEY(job_id) REFERENCES jobs(job_id));";
my manager table is populated with the following information
1|john
2|bob
let's say manager john has added two jobs,jobTitle jobA and jobB
then my insert statement code will look like this.http://pastebin.com/0E8CzPgX
then my jobs tables is populated with the following information
1|jobA
2|jobB
the final step is to take the id of john(manager id = 1) and the two jobsId(1,2) and add it inside
the add table. I don't have an idea of how should I code
so that the add table will become like this.
add table
manager_id|job_id|date
1 | 1 |30-01-2014
1 | 2 |30-01-2014
please advise.thanks
Do you mean something like
sql = "INSERT INTO Add(manager_id,jobId,date) VALUES (?,?,?);";
?
Your problem seems to be that you defined jobID to be the primary key of the table Add, which you don't need.
jobId INTEGER PRIMARY KEY NOT NUL
A common approach to many-to-many relations in a database is to include an intermediate table.
This intermediate table (let's call it Manager_jobs) would have at least 2 columns, both referring to other tables via foreign key. The first attribute would be the primary key of Manager, the second one the primary key of jobs.
Each time you add a job, you just add an entry to Manager_jobs with the foreign keys respectively.
So, Manager_jobs would look like this:
ManagerID | JobID
==========|======
4 | 2
3 | 2
4 | 1
As you can see, Manager_jobs can encode that a Manager has multiple jobs assigned and vice versa.
This approach, of course, requires you to have some form of primary key for both data tables.
I am using this link.
I have connected my cpp file with Eclipse to my Database with 3 tables (two simple tables
Person and Item
and a third one PersonItem that connects them). In the third table I use one simple primary and then two foreign keys like that:
CREATE TABLE PersonsItems(PersonsItemsId int not null auto_increment primary key,
Person_Id int not null,
Item_id int not null,
constraint fk_Person_id foreign key (Person_Id) references Person(PersonId),
constraint fk_Item_id foreign key (Item_id) references Items(ItemId));
So, then with embedded sql in c I want a Person to have multiple items.
My code:
mysql_query(connection, \
"INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8);");
printf("%ld PersonsItems Row(s) Updated!\n", (long) mysql_affected_rows(connection));
//SELECT newly inserted record.
mysql_query(connection, \
"SELECT Order_id FROM PersonsItems");
//Resource struct with rows of returned data.
resource = mysql_use_result(connection);
// Fetch multiple results
while((result = mysql_fetch_row(resource))) {
printf("%s %s\n",result[0], result[1]);
}
My result is
-1 PersonsItems Row(s) Updated!
5
but with VALUES (1,1,5), (1,1,8);
I would like that to be
-1 PersonsItems Row(s) Updated!
5 8
Can somone tell me why is this not happening?
Kind regards.
I suspect this is because your first insert is failing with the following error:
Duplicate entry '1' for key 'PRIMARY'
Because you are trying to insert 1 twice into the PersonsItemsId which is the primary key so has to be unique (it is also auto_increment so there is no need to specify a value at all);
This is why rows affected is -1, and why in this line:
printf("%s %s\n",result[0], result[1]);
you are only seeing 5 because the first statement failed after the values (1,1,5) had already been inserted, so there is still one row of data in the table.
I think to get the behaviour you are expecting you need to use the ON DUPLICATE KEY UPDATE syntax:
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, order_id)
VALUES (1,1,5), (1,1,8)
ON DUPLICATE KEY UPDATE Person_id = VALUES(person_Id), Order_ID = VALUES(Order_ID);
Example on SQL Fiddle
Or do not specify the value for personsItemsID and let auto_increment do its thing:
INSERT INTO PersonsItems( Person_Id, order_id)
VALUES (1,5), (1,8);
Example on SQL Fiddle
I think you have a typo or mistake in your two queries.
You are inserting "PersonsItemsId, Person_Id, Item_id"
INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8)
and then your select statement selects "Order_id".
SELECT Order_id FROM PersonsItems
In order to achieve 5, 8 as you request, your second query needs to be:
SELECT Item_id FROM PersonsItems
Edit to add:
Your primary key is autoincrement so you don't need to pass it to your insert statement (in fact it will error as you pass 1 twice).
You only need to insert your other columns:
INSERT INTO PersonsItems(Person_Id, Item_id) VALUES (1,5), (1,8)
I have a text file with rows (lines). Each row is a record in database table. I read this file and fill database.
Tables creating command:
CREATE TABLE gosts(number TEXT PRIMARY KEY, userNumber TEXT, status TEXT, date TEXT, title TEXT, engTitle TEXT, description TEXT, mainCategory INTEGER, category INTEGER, subCategory INTEGER);
Inserting query:
INSERT INTO gosts VALUES ("30331.8-95", "ÃÎÑÒ 30331.8-95", "Äåéñòâóþùèé", "01.07.1996", "Ýëåêòðîóñòàíîâêè çäàíèé. ×àñòü 4. Òðåáîâàíèÿ ïî îáåñïå÷åíèþ áåçîïàñíîñòè. Îáùèå òðåáîâàíèÿ ïî ïðèìåíåíèþ ìåð çàùèòû äëÿ îáåñïå÷åíèÿ áåçîïàñíîñòè. Òðåáîâàíèÿ ïî ïðèìåíåíèþ ìåð çàùèòû îò ïîðàæåíèÿ ýëåêòðè÷åñêèì òîêîì", "Electrical installations of buildings. Part 4. Protection for safety. Applisation of protective measues for safety. Measures of protection against electric shock", "Íàñòîÿùèé ñòàíäàðò óñòàíàâëèâàåò îáùèå òðåáîâàíèÿ ïî ïðèìåíåíèþ ìåð çàùèòû äëÿ îáåñïå÷åíèÿ áåçîïàñíîñòè è òðåáîâàíèÿ ïî ïðèìåíåíèþ ìåð çàùèòû îò ïîðàæåíèÿ ýëåêòðè÷åñêèì òîêîì ïðè ýêñïëóàòàöèè ýëåêòðîóñòàíîâîê çäàíèé", 37, 333, 628);
Please ignore encoding problems. Source file has cp1251 encoding, but inserting sample is taken from console. I tried to use utf-8 but had the same problem.
SQLite using code above:
if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) {
...
}
Function calling doesn't return SQLITE_OK. And I gea error message by:
string error = sqlite3_errmsg(database);
if(error != "not an error") cout << query << " " << error << endl;
Strangely, some records are inserted without error and I can't find differences between good and bad records.
I can provide more information if needed.
I would bet that the difference between the good and bad rows were whether or not the value associated with the 'number' column was already in the table.
This is one of the reasons that table designs usually do not use TEXT valued columns for PRIMARY KEYs.
If it is possible to re-create your table, I would create an ID field responsible for being the PRIMARY KEY for your table. Further enable the IDENTITY property for auto increment of your primary key value.
This should prevent insertion failure due to having duplicate values in the 'number' column.
Now if values in 'number' column must be unique then you should add a UNIQUE constraint on that column.
NOTE: The UNIQUE will yield the same error you are currently receiving as it appears you are trying to add multiple rows with the same value for column'number'
Review the SQLite CREATE TABLE documentation for more details.