How to fix an SQL design - sql

I'm doing the study of a medical software. This software asks the patients questions about their symptoms and from them it can determine the possible pathologies. My study involves comparing the symptoms and pathologies found by the software with those from the hospital.
In order to make my work easier, I decided to enter the data in a database made with javadb on netbeans 8.2.
But it seems like that I did something wrong since my statement doesn't work.
I thank you in advance anybody who would take the time to help me.
SQL design:
Create table Patients(
nip varchar(32) primary key,
sexe varchar(8) not null,
age int not null,
dateArrivee timestamp not null,
constraint ck_sexe check(sexe='Male' or sexe='Female'),
constraint ck_age check (age>=0)
);
Create table Symptoms(
symptomID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
symptom varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);
Create table Pathologies(
pathologyID int primary key generated always as identity (start with 1,
increment by 1),
nip varchar(32) not null,
pathology varchar(64),
origin varchar(16) not null,
foreign key (nip) references Patients(nip),
constraint ck_origin check (origin='SOFTWARE' or origin='HOSPITAL')
);
Values entered:
Insert into Patients values ('001','Male', 25, '2019-05-27 14:00:00');
Insert into Patients values ('002', 'Female', 30, '2019-05-26 15:00:00');
Insert into Symptoms values (, '001', 'Headache', 'SOFTWARE');
Insert into Pathologies values (,'001', 'Fever', 'SOFTWARE');
Insert into Symptoms values (,'001', 'Stomache', 'HOSTPITAL');
Insert into Pathologies values (, '001', 'Gastro-enteritis', 'HOSPITAL');
Insert into Symptoms values(,'002', 'Headache', 'SOFTWARE');
Insert into Pathologies values (,'002', 'Unknow', 'SOFTWARE');
SQL statement:
Select *
from (Patients inner join
Symptoms
on Patients.nip = Symptoms.nip
) inner join
Pathologies
on Symptoms.nip = Pathologies.nip
where Symptoms.origin = 'MEDVIR' and
Pathologies.origin = 'MEDVIR';
So sorry I forgot to put the errors I'm getting.
SQL design:
First I have an error concerning the auto_incrementation, even thought this was the good method. It says that the syntax is incorrect near the 'generated'.
Values entered:
Here I have an error concerning the a wrong syntax near the coma (',').
SQL statement:
Lastly I have an error saying that the object 'Patients' is unavaible.

If I am not wrong, you are trying to fetch entries where 'Origin' = 'MEDVIR'
Although, none of your insert statements have Origin as 'MEDVIR'
Please check below,
Select *
from (Patients inner join
Symptoms
on Patients.nip = Symptoms.nip
) inner join
Pathologies
on Symptoms.nip = Pathologies.nip
where Symptoms.origin IN ('SOFTWARE', 'HOSPITAL') and
Pathologies.origin IN ('SOFTWARE', 'HOSPITAL');
Also, some of your INSERT statement has an extra comma before the values, which would cause a syntax error.

Related

Constraint not working as desired for my INSERT?

I am creating a Table named "Cliente" with some constraints on it as it follows:
CREATE TABLE public."Cliente" (
"K_CODCLIENTE" numeric(5) NOT NULL,
"N_NOMBRE1" varchar(15) NOT NULL,
"N_NOMBRE2" varchar(15) NOT NULL,
"N_APELLIDO1" varchar(15) NOT NULL,
"N_APELLIDO2" varchar(15),
"N_DIRECCION" varchar(50) NOT NULL,
"Q_TELEFONO" numeric(10) NOT NULL,
"K_CODREF" numeric(5),
"I_TIPOID" varchar(2) NOT NULL,
"Q_IDENTIFICACION" varchar(10) NOT NULL,
CONSTRAINT "PK_Cliente" PRIMARY KEY ("K_CODCLIENTE"),
CONSTRAINT "UQ_ID_TIPOID_CLIENTE" UNIQUE ("I_TIPOID","Q_IDENTIFICACION"),
CONSTRAINT "CK_CODCLIENTE" CHECK ("K_CODCLIENTE" >= 100),
CONSTRAINT "CK_Q_IDENTIFICACION" CHECK ("Q_IDENTIFICACION" IN ('CC', 'PA', 'CE', 'NI', 'OT'))
);
When I try to insert some values on it:
INSERT INTO "Cliente"
VALUES ('101','Juan','Felipe','Ortiz','Rojas','AK 15 no. 28-05','3101125507',null,'CC','51111111');
I get the following error (in PostgreSQL 14, on Fedora):
[23514] ERROR: new row for relation "Cliente" violates check constraint "CK_Q_IDENTIFICACION"
Detail: Failing row contains (101, Juan, Felipe, Ortiz, Rojas, AK 15 no. 28-05, 3101125507, null, CC, 51111111).
I am trying to restrict the "Q_IDENTIFICACION" column so it can only be filled with 'CC', 'PA', 'CE, 'NI' or 'OT'.
Maybe I'm doing something wrong when declaring the constraint "CK_Q_IDENTIFICACION"?
Seems like you messed up the mapping of values and are trying to insert '51111111' to "Q_IDENTIFICACION".
Consider this more revealing variant with a formatted list of target columns:
INSERT INTO "Cliente"
("K_CODCLIENTE", "N_NOMBRE1", "N_NOMBRE2", "N_APELLIDO1", "N_APELLIDO2", "N_DIRECCION" , "Q_TELEFONO", "K_CODREF", "I_TIPOID", "Q_IDENTIFICACION")
VALUES ('101' , 'Juan' ,'Felipe' , 'Ortiz' , 'Rojas' , 'AK 15 no. 28-05', '3101125507', NULL , 'CC' , '51111111'); -- !
Maybe you want to switch the last two column names in the table definition - and (not) adapt the VALUES list in the INSERT accordingly? (varchar(2) vs. varchar(10) seems switched as well.)
For persisted code, it's generally advisable to spell out target columns in an INSERT command in any case.
Asides:
Reconsider all these pesky double-quoted upper case identifiers. See:
Are PostgreSQL column names case-sensitive?
Consider plain type text instead of varchar(n) with strikingly tight character limits. See:
Any downsides of using data type "text" for storing strings?

Cannot create Access tables through SQL view

I'm trying to create 3 access tables in SQL view on Microsoft Access but whenever I try to execute it, I receive the following error. 'Syntax Error in CREATE TABLE statement'.
Please find my code below.
CREATE TABLE Book (
Book_ID int,
Book_Title varchar (30),
PRIMARY KEY (Book_ID)
);
CREATE TABLE Users (
User_ID int,
User_Name varchar (30),
PRIMARY KEY (User_ID)
);
CREATE TABLE Borrows (
User_ID int,
Book_ID int,
B_ID int,
PRIMARY KEY(B_ID),
FOREIGN KEY(User_ID) REFERENCES Users(User_ID),
FOREIGN KEY(Book_ID) REFERENCES Book(Book_ID)
);
INSERT INTO Book VALUES (101, 'The Hobbit'), (102, 'To Kill a Mockingbird');
INSERT INTO Users VALUES (1, 'Stephen'), (2, 'Tom'), (3,' Eric');
INSERT INTO Borrows VALUES (3, 102, 1), (1, 101, 2);
Appreciate any feedback I can get, have a good day.
Your first CREATE TABLE executed flawlessly from the query designer in Access 2010. However my preference is to include the PRIMARY KEY constraint as part of the field definition:
CREATE TABLE Book (
Book_ID int PRIMARY KEY,
Book_Title varchar (30)
);
That variation also executed successfully.
I suspect you have at least 2 issues to resolve:
Access does not allow you to execute more than one SQL statement at a time (as Heinzi and Albert mentioned). You must execute them one at a time.
In Access, INSERT ... VALUES can only be used to add one row at a time. Revise your inserts accordingly.
IOW, split the first one into 2 statements which you then execute individually:
-- INSERT INTO Book VALUES (101, 'The Hobbit'), (102, 'To Kill a Mockingbird');
INSERT INTO Book VALUES (101, 'The Hobbit');
INSERT INTO Book VALUES (102, 'To Kill a Mockingbird');
Then split and execute the remaining inserts similarly.
Your code example use SQL Server (T-SQL) syntax, not MS Access syntax.
The syntax for Access' CREATE TABLE statement is documented here:
https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/create-table-statement-microsoft-access-sql
The most obvious differences seem to be there is no varchar type and that PRIMARY KEY needs a constraint name if specified in an extra line. There might be more, see the article and its examples for details. I also suggest that you submit your statements one-by-one, instead of submitting a complete ;-separated batch; I'm not sure Access queries even support the latter.

Why do I receive error 1241 when trying to Create and Insert data into a new table (on phpMyAdmin)?

I am trying to create a new table and insert values into it however I keep receiving "#1241 - Operand should contain 1 column(s)".
Please could someone help to identify what is wrong with my code as I am unsure what this error is referencing?
The code I am inserting into the phpMyAdmin database under the SQL tab. I have tried to remove the auto increment attributes and have tried looking at other examples to check my syntax, but I can't spot the issue. Some guidance on this would be greatly appreciated.
The code I entered begins like this:
# AppSoft Project - Greg Roberts
DROP table if exists Department;
DROP table if exists Role;
DROP table if exists User;
DROP table if exists Appraisal;
DROP table if exists Question;
DROP table if exists Answer;
CREATE table Department(
DeptID int NOT NULL AUTO_INCREMENT,
DeptName varchar(30) NOT NULL,
primary key (DeptID));
INSERT into Department values(
(00, 'SuperAdmin'),
(01, 'Support Staff'),
(02, 'Teaching Staff'),
(03, 'SLT'));
CREATE table Role(
RoleID int NOT NULL AUTO_INCREMENT,
RoleTitle varchar(30) NOT NULL,
primary key (RoleID));
INSERT into Role values(
(00, 'SuperAdmin'),
(01, 'Office Administrator'),
(02, 'Teaching Partner'),
(03, 'Mid Day Supervisor'),
(04, 'Cooks'),
(05, 'Cleaners'),
(06, 'Maintenance'),
(07, 'Teacher'),
(08, 'Department Head'),
(09, 'SENCO'),
(10, 'Head Teacher'),
(11, 'Executive Head'));
Error Code that Occurs
You dont need to insert primary keys, if they are set to auto_increment.
DeptID int NOT NULL AUTO_INCREMENT
Just insert the department name, there are no additional braces required for Values.
INSERT into Department( DeptName) values
('SuperAdmin'),
('Support Staff'),
('Teaching Staff'),
('SLT');
You would need to do the same for Role table as well.
Also if you try to insert 0 into the primary key, it will actually insert 1 you can read about it in the Standard Docs
you seem to be getting the error because your first record inserts 1 into the table and then your second record tries to insert 1 again in the primary key column

How to insert value into foreign key in SQL server? (Avoid the duplicate key.)

I create two table. They connected by primary key and foreign key. When I insert new values, it said cannot insert duplicate key in object. Here are my tables
create table person (
sinNum int primary key not null,
gender varchar(6) not null check (gender in ('male','female')) default 'female',
age int not null check (age>=18 and age<=100),
emailAddr varchar (50) not null,
phoneNum int not null,
)
create table employee (
empId int identity (1,1) unique,
lastName varchar (30) not null,
firstName varchar (30) not null,
sinNum int unique foreign key references person (sinNum),
departmentId int foreign key references department (departmentId),
position varchar (20) not null check (position in ('clerk','assistant','supervisor','manager','director','president')) default'clerk',
baseSalary float not null
)
Here are my insert statements
insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)
insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
Here are the error messages
Violation of PRIMARY KEY constraint 'PK__person__228E26BE3A9512B2'.
Cannot insert duplicate key in object 'dbo.person'. The duplicate key
value is (333).
Can anyone show me the way please? Many thanks
You have not set sinNum as identity. Make it auto incremented and then change your insert query as below.
insert into person (sinNum,gender,age,emailAddr, phoneNum) values ((SELECT ISNULL(MAX(sinNum)+1,0) FROM person WITH(SERIALIZABLE, UPDLOCK)),
'female', 24, 'dds', 2121)
You can use simpler version also, but it doesn't guarantee concurrency:
insert into person (sinNum,gender,age,emailAddr, phoneNum) values (NULL,
'female', 24, 'dds', 2121)
Since sinNum is your primary key, if you try to INSERT a new row containing the same value it will reject you.
Just use the following query to delete the rows before adding it again.
DELETE FROM person WHERE sinNum = 333;
You can also update/merge the row or simply not add it, since you have done it already.
As the column 'sinum' is primary key, you can't define it explicitly.
So please have a try with below.
Insert into person (gender,age,emailAddr, phoneNum) values ( 'female', 24, 'dds', 2121)
Declare #sinnum=IDENT_CURRENT('Person')
If ##error=0
Insert into employee(lastName,firstName, sinnum, departmentId, position,baseSalary) values ('Snow','John',#sinnum,20,'clerk',4000)
Ident_current will save the last inserted primary key value in the mentioned table. Saving that value in a temporary variable, inorder to use the same value as FK in the employee table.
##error used here to ensure insert on employee table only on successful insert made in person table.
What's happening here is that your insert on Person table is violating the primary key constraint. So we can use this exception as an antidote.
You can make use of Try-Catch statement and can implement your further logic in the catch block.
/* You an use #output parameter too */
Declare #output bit=1
BEGIN TRY
insert into person (sinNum,gender,age,emailAddr, phoneNum) values (333,
'female', 24, 'dds', 2121)
insert into employee(lastName,firstName, sinNum, departmentId,
position,baseSalary) values ('Snow','John',333,20,'clerk',4000)
print 'Record inserted in both table'
set #output=1
END TRY
BEGIN CATCH
if error_message() like 'Violation of PRIMARY KEY constraint%'
Begin
/* Do whatever you like to do here */
/* You can delete the existing record if you want */
print 'Record already exists is Person table' --just the intimation
set #output=0
End
else
print 'other exception' --just the intimation
END CATCH
You can delete the existing record in catch block or can make new transaction using #output variable.. Hope it works for you.

oracle error: not enough values

i have a table donor_master:
create table donor_master
(
donor_id number(10) primary key not null,
dob date not null,
age number(3) not null,
gender char(1) not null,
blood_group char(3),
contact_no number(10),
address varchar(50) not null,
city varchar(10) not null,
pin number(10) not null,
state varchar(10) not null,
branch_registration_id number(5) references branch_master(branch_id)
);
when i try to insert into the table in a procedure insert_donor_master, i get "not enough values" error on compilation.
this is the procedure:
create or replace procedure insert_donor_master(
vdob donor_master.dob%type,
vage donor_master.age%type,
vgender donor_master.gender%type,
vblood_group donor_master.blood_group%type,
vcontact_no donor_master.contact_no%type,
vaddress donor_master.address%type,
vcity donor_master.city%type,
vpin donor_master.pin%type,
vstate donor_master.state%type,
vbranch_registration_id donor_master.branch_registration_id%type
)
is
begin
insert into donor_master values (sq_donor_master.nextval, vdob, vage, vgender, vblood_group, vcontact_no, vaddress, vcity, vpin, vstate, vbranch_registration_id);
commit;
end;
What is the problem?
Thanks.
Oracle hurls ORA-00947 when we specify an INSERT statement which doesn't have a value for every column in the table.
Now, the CREATE TABLE statement you posted shows a table with eleven columns. And the stored procedure code you posted shows an insert statement with eleven values in the VALUES (...) clause.
So, the explanations are:
you have a configuration management issue, and you're running the wrong version of the stored procedure or the wrong version of the table
you have a configuration management issue, and the actual structure of the table isn't what you think it is (doesn't match your CREATE TABLE script)
you aren't really getting an ORA-00947 error
Note that if you don't want to populate every row you can specify a projection of the relevant columns before the VALUES clause. For instance, if you just wanted to populate the mandatory columns you would code this:
insert into donor_master
(donor_id, dob, age, gender, address, city, pin, state )
values (sq_donor_master.nextval, vdob, vage, vgender, vaddress, vcity, vpin, vstate)
All that matters is that the number of values matches the number of columns.
The complete syntax for INSERT statements is in the documentation. enter link description hereFind out more.