PostgreSQL table does not exist - sql

drop table Employee;
CREATE TABLE Employee
( EmployeeID integer,
FirstName varchar(24),
LastName varchar(24),
Email varchar(48),
PhoneNumber varchar(12),
HotelID integer
PRIMARY KEY (EmployeeID),
);
INSERT INTO Employee VALUES (1, ‘James’, ‘Jenkins’, ‘jj#gmail.com’, ’0412181111’, 1);
INSERT INTO Employee VALUES (22, ‘Roy’, ‘Bond’, ‘jb#gmail.com’, ‘0418246192’, 1);
INSERT INTO Employee VALUES (14, ‘Rachel’, ‘Green’, ‘rg#gmail.com’, ‘0468129367’, 1);
INSERT INTO Employee VALUES (96, ‘Eddard’, ‘Stark’, ‘es#gmail.com’, ‘0458192716’, 1);
INSERT INTO Employee VALUES (77, ‘Anna’, ‘Nguyen’, ‘an#gmail.com’ , ‘0418238694’, 1);
Error: "psql:employee:1: ERROR: table "employee" does not exist"
What is the way that the error can be fixed?
Link to the entire doc if anyone wants to take a look: https://docs.google.com/document/d/1r4E7yz4XJxLmO3rmkH4YBVOGfYN5PkhcDSJUyuy7qxw/edit?usp=sharing

Your create statement has a comma(,) missing before declaring the primary key. Therefore the table is not getting created. This this:
CREATE TABLE Employee
( EmployeeID integer,
FirstName varchar(24),
LastName varchar(24),
Email varchar(48),
PhoneNumber varchar(12),
HotelID integer,
PRIMARY KEY (EmployeeID),
FOREIGN KEY (HotelID) REFERENCES Hotel
);

The table Employee might not be already created in your database when you are trying to run above snippet. Always have an IF EXISTS check before dropping a table or stored procedure or function.
Your drop query should be.
drop table if exists `Employee`;

Related

Triggers working correctly, but raise application error causing some errors with insert statements

I have my code shown below. Everything is working correctly but when my insert statements violate the trigger it throws errors because of my raise_application_error.
--Drop tables in case they were created previously
DROP TABLE enrollment Purge;
DROP TABLE offering Purge;
DROP TABLE faculty Purge;
DROP TABLE course Purge;
DROP TABLE student Purge;
--Create student table
CREATE TABLE student(StdID number(3) constraint student_StdID_PK primary key,
StdFN varchar2(10),
StdLN varchar2(15),
StdCity varchar2(15),
StdState char(2),
StdZip number(5),
StdMajor varchar2(4),
StdClass char(2),
StdGPA number(2,1),
StdBalance NUMBER (12,2));
--create a table for courses and their descriptions
CREATE TABLE course(CourseNo varchar2(8) constraint course_courseNo_PK primary key,
CrsDesc varchar2(40),
CrsCredits number(1));
--create faculty table
CREATE TABLE Faculty(FacID number(4) constraint faculty_FacID_PK primary key,
FacFN varchar2(10),
FacLN varchar2(15),
FacDept varchar2(4),
FacRank varchar2(4),
FacHireDate date,
FacSalary number(6),
FacSupervisor number(4));
--create table for offered courses
CREATE TABLE Offering(OfferNo number(4) constraint offering_OfferNo_PK primary key,
CourseNo varchar(8)constraint offering_crs_no references course(courseno),
OffTerm varchar2(6),
OffYear number(4),
OffLoca varchar(6),
OffTime varchar(8),
OffDay varchar(5),
FacSSN number(4)constraint offering_fac_FK references faculty(facID));
--create table for student enrollment
CREATE TABLE enrollment(StdID number(3),
OfferNo number(4),
EnrGrade char(2),
constraint enrollment_PK primary key (StdID,OfferNo),
constraint enrollment_std_ID foreign key(StdID) references student(stdID),
constraint enrollment_class_ID foreign key(offerno) references offering(offerno));
CREATE OR REPLACE TRIGGER UNPAID_BALANCE
BEFORE INSERT ON STUDENT
FOR EACH ROW
DECLARE
BAL NUMBER;
BEGIN
BAL := :NEW.STDBALANCE;
IF BAL > 500
THEN
RAISE_APPLICATION_ERROR(-20001, 'Your balance is too high to register. Please pay to continue.');
END IF;
END;
/
CREATE OR REPLACE TRIGGER ENROLL_MAX
BEFORE INSERT ON ENROLLMENT
FOR EACH ROW
DECLARE
NOFSTUDENTS BINARY_INTEGER;
BEGIN
SELECT COUNT(*) INTO NOFSTUDENTS
FROM ENROLLMENT
WHERE OFFERNO = :NEW.OFFERNO AND ENRGRADE IS NULL;
DBMS_OUTPUT.PUT_LINE(NOFSTUDENTS);
IF (NOFSTUDENTS + 1) > 2
THEN
RAISE_APPLICATION_ERROR(-20003, 'EXCEED MAX NO OF STUDENTS ALLOWED');
END IF;
END;
/
--populate student table
INSERT INTO student values(101,'Joe','Smith','Eau Clare','WI',18121,'IS','FR',3.8,225.25);
INSERT INTO student values(102, 'Rob','King', 'Melrose', 'MN', 56352, 'IS','JR',3.2,120.98);
INSERT INTO student values(103, 'Dan','Robinson', 'Sartell', 'MN', 98042, 'IS','JR',3.6, 36);
INSERT INTO student values(104,'Sue','Williams','St.Cloud','MN',56301,'ACCT','SR',3.2,2386.55);
INSERT INTO student values(105,'Don','Robinson','St.Paul','MN',55103,'MKTG','SR',3.4, 306);
--populate course table
INSERT INTO Course values('CSCI 200','Elements of Computing',3);
INSERT INTO Course values('IS 250','Application of Program Dev. I',3);
INSERT INTO Course values('IS 251','Application of Program Dev. II',3);
INSERT INTO Course values('IS 454', 'Data Mining for Decision Support',3);
INSERT INTO Course values('IS 356','Systems Analysis and Design I',3);
INSERT INTO Course values('IS 460', 'Project Management',3);
INSERT INTO Course Values('ACCT 291','Accounting Principles II',3);
INSERT INTO Course values('IS 443','Database Design',3);
--populate faculty table
INSERT INTO faculty values(9001,'Leonard','Vince','IS','ASST','12-Apr-1997',67000,9003);
INSERT INTO faculty values(9002,'Victor','Strong','CSCI','ASSO','8-Aug-1999',70000,9003);
INSERT INTO faculty values(9003,'Nicki','Colan','IS','PROF','20-Aug-1981',75000,9010);
INSERT INTO faculty values(9004,'Fred','Wells','ACCT','ASST','28-Aug-1996',60000,9010);
INSERT INTO faculty values(9010,'Chris','Macon','ACCT','ASST','4-Aug-1980',75000,Null);
--populate offering table
INSERT INTO offering values(2201,'CSCI 200','Spring',2017,'ECC135','10:30AM','MWF',9002);
INSERT INTO offering values(2202,'CSCI 200','Spring',2017,'ECC135','8:00AM','MWF',9002);
INSERT INTO offering values(1102,'ACCT 291','Spring',2017,'CH 14A','2:00AM','MWF',9004);
INSERT INTO offering values(2203,'IS 356','Fall',2017,'CH494','3:30AM','TTH',9001);
INSERT INTO offering values(2204,'IS 251','Fall',2017,'CH494','12:30AM','TTH',9003);
INSERT INTO offering values(1101,'ACCT 291','Fall',2017,'CH350','12:30AM','TTH',9010);
INSERT INTO offering values(2205,'IS 443','Fall',2017,'CH494','9:30AM','MWF',9003);
--populate enrollment table
INSERT INTO enrollment values(101,2201,'A');
INSERT INTO enrollment values(102,2202,'B');
INSERT INTO enrollment values(102,2203,null);
INSERT INTO enrollment values(103,2203,null);
INSERT INTO enrollment values(103,2201,'C');
INSERT INTO enrollment values(103,1101,null);
INSERT INTO enrollment values(104,2202,'A');
INSERT INTO enrollment values(101,2203,null);
INSERT INTO enrollment values(101,1101,null);
INSERT INTO enrollment values(101,2205,null);
INSERT INTO enrollment values(102,2205,null);
INSERT INTO enrollment values(104,2205,null);
Is there a way I can make this look cleaner/better in the script output section because one specific case is this error message that pops up because of the raise application error.
Error starting at line : 129 in command -
INSERT INTO enrollment values(104,2202,'A')
Error report -
ORA-02291: integrity constraint (ADMIN_BF.ENROLLMENT_STD_ID) violated - parent key not found
The error that you are facing is clear enough. There is not student 104 in the table, so you cannot create a dependent record in enrollment. This error is not related to your triggers, but to your data.
Now let's look at the insert statement for that particular user:
INSERT INTO student values(104,'Sue','Williams','St.Cloud','MN',56301,'ACCT','SR',3.2,2386.55);
You are attempting to input a balance of 2386.55. But your trigger UNPAID_BALANCE prevents balances that are above 500, so that insert raises application error "Your balance is too high to register", which is the root cause of the problem. You need to fix that insert.
Side note: there is another problem lurking in the last series of inserts into enrollments. Trigger ENROLL_MAX allows only two students per OFFERNO, but you are attempting to assign three students to offer 2203, and three as well to offer 2205. This will raise application error "EXCEED MAX NO OF STUDENTS ALLOWED".

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.

ORA-00936: missing expression error when inserting values

I spend lot of time searching where i made the mistake but i was unable to find it when its going to insert the last record there is a error message showing "ORA-00936: missing expression" How to solve this please help me
create type pearson_types as object(
name varchar2(50),
sysID char(6)
)NOT FINAL;
create type doctor_types under pearson_types(
regNo char(10),
specialization varchar2(25)
)
create table doctor of doctor_types(
regNo primary key
)
create type hospVisits_types as object(
hosChg float,
vDate varchar2(20),
refDoc REF doctor_types,
docChg float
)
create type hospvisits_tbl_types as table of hospVisits_types
create type phone_arr as VARRAY(3) of char(10)
create type patient_types under pearson_types
(
id char(10),
dob varchar(20),
phone phone_arr,
hospVisits hospvisits_tbl_types
)
create table patients of patient_types(
id primary key
)nested table hospVisits store as Hospital_tables
alter table Hospital_tables add scope for (refDoc) is doctor
insert into doctor values ('Dr.k.perera','D001','1223441234','Gynecologist');
insert into doctor values ('Dr.p.weerasingha','D002','1234421131','Dermatalogist');
insert into doctor values ('Prof .S. Fernando','D003','2342111322','Pediatrician');
insert into doctor values ('Dr.k.Sathgunanathan','D004','2344114344','Pediatrician');
insert into patients values('Sampath Weerasingha','P001','732821122V','23-JAN-73',phone_arr('0332124222'),hospvisits_tbl_types(hospVisits_types(50.00,'24-MAY-06',select ref (a) from doctor a where a.regNo='1223441234',500.00)))
Add parentheses to SELECT statements inside a SQL statement:
insert into patients values(
'Sampath Weerasingha','P001','732821122V','23-JAN-73',phone_arr('0332124222'),
hospvisits_tbl_types(hospVisits_types(50.00,'24-MAY-06',
( -- ADD ME
select ref (a) from doctor a where a.regNo='1223441234'
) -- ADD ME
,500.00))
);

SQL datable query to insert multiple column values

How to add multiple values in a single column of table in SQL? My table looks like this:
Create table emp
(
id number(5),
name varchar(25),
phone varchar(25)
);
Now I want to add values and multiple phones in the phone column. How to do that? I tried using
insert into emp values (id, name, phone)
values (1, lee, (23455, 67543));
but this is not working
Use two insert statements instead
insert into emp values (id, name,phone) values (1,'lee','23455');
insert into emp values (id, name,phone) values (1,'lee','67543');
or If you want to store both the values in single row
insert into emp values (id, name,phone) values (1,'lee','23455,67543');
Here table is not normalised. You either need to store Phone Number info in separate table or use two different column in same table.
Try changing you table design like this.
EMP table
CREATE TABLE emp
(
emp_id INT IDENTITY(1, 1) PRIMARY KEY,
name VARCHAR(25)
);
PhoneNumber Table
CREATE TABLE PhoneNumber
(
phoneno_id INT IDENTITY(1, 1),
emp_id INT,
Phone_Number int,
Cell_Number Int,
FOREIGN KEY (emp_id) REFERENCES emp(emp_id)
)
Note : Auto increment syntax may differ based on the database you are using.
The proper and only real well-designed way to do this in a relational setting is to use a separate table for your phones (this is in SQL Server specific syntax - it might be slightly different, depending on which concrete database system you're using):
Create table emp
(
id INT PRIMARY KEY,
name varchar(25)
)
create table phone
(
phoneId INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
empid INT NOT NULL,
phone varchar(25) NOT NULL,
CONSTRAINT FK_Phone_Emp
FOREIGN KEY(empid) REFERENCES dbo.emp(id)
);
and then you insert the employee data into emp :
insert into emp(id, name)
values (1, lee);
and the phones into phone:
insert into phone(empid, phone) values(1, 23455);
insert into phone(empid, phone) values(1, 67543);
With this setup, you have proper normalization for the database, and you can store as many phones as you like, for each employee.