How to use INSERT INTO SELECT - sql

CREATE TABLE EMPLOYEES (
EMPLOYEEID INT NOT NULL,
DEPARTMENTID INT NOT NULL,
);
CREATE TABLE MANAGERS (
EMPLOYEEID INT NOT NULL,
DEPARTMENTID INT NOT NULL,
ALTER_TIMESTAMP TIMESTAMP NOT NULL
);
I want to insert EMPLOYEES.EMPLOYEEID, EMPLOYEES.DEPARTMENTID, ALTER_TIMESTAMP to MANAGERS table using INSERT INTO SELECT. (ALTER_TIMESTAMP col is current time)
I want this result
enter image description here
this is my code
INSERT INTO MANAGERS
(EMPLOYEEID, DEPARTMENTID, ALTER_TIMESTAMP)
SELECT EMPLOYEEID, DEPARTMENTID, to_char(ALTER_TIMESTAMP, 'YYYY-MM-DD HH24:MI:SS:FF3')
FROM EMPLOYEES, DUAL;
but "ORA-00904: "DUAL"."ALTER_TIMESTAMP": invalid identifier"

You have no column named "alter_timestamp" in your table, this is the cause of the error message.
Try the next insert statement:
INSERT INTO MANAGERS
(EMPLOYEEID, DEPARTMENTID, ALTER_TIMESTAMP)
SELECT EMPLOYEEID, DEPARTMENTID, CURRENT_TIMESTAMP
FROM EMPLOYEES;

Related

oracle trigger pl sql

I have a database user that contains four tables department, employee, address and contact info, then stored 5 Records in each table, and wrote the PL/SQL Statement for the following:
Stored a record into employee, address and contact using trigger.
the insert into view is not working ! it results in error ? can you guys help me with this ?
this is my code :
-- Create Tables :
CREATE TABLE address (
code int primary key,
city varchar2(30),
street varchar2(30)
);
create table Department (
DepId int primary key ,
Dep_Name varchar2(30) ,
Dep_adress varchar(30));
create table Employee (
Emp_Id int primary key ,
firstName varchar2(30),
lastName varchar2(30),
salary int,
Dep_Id int references Department (DepId),
Code int references address (code));
CREATE TABLE contact_info (
email varchar2(30) primary key ,
phone int ,
EmpId int references Employee (Emp_Id));
-- insert :
insert into Department values (1,'IT','Amman');
insert into Department values (2,'CS','Jerash');
insert into Department values (3,'accounting','Amman');
insert into Department values (4,'managment','Amman');
insert into Department values (5,'employment','Amman');
insert into address values (50,'Amman','AAA');
insert into address values (60,'Amman','AAB');
insert into address values (70,'Amman','AAC');
insert into address values (80,'Jerash','AAD');
insert into address values (90,'Irbid','AAE');
insert into Employee (Emp_Id,firstName,lastName,salary,Dep_Id,Code) values (1,'john' , 'samo' , 1000 , (select DepId from Department where Dep_Name = 'IT'),(select code from address where street = 'AAA'));
insert into Employee (Emp_Id,firstName,lastName,salary,Dep_Id,Code) values (2,'mark' , 'wol' , 2000 , (select DepId from Department where Dep_Name = 'IT'),(select code from address where street = 'AAB'));
insert into Employee (Emp_Id,firstName,lastName,salary,Dep_Id,Code) values (3,'ahmad' , 'moh' , 1100 , (select DepId from Department where Dep_Name = 'IT'),(select code from address where street = 'AAC'));
insert into Employee (Emp_Id,firstName,lastName,salary,Dep_Id,Code) values (4,'maher' , 'imk' , 1700 , (select DepId from Department where Dep_Name = 'CS'),(select code from address where street = 'AAD'));
insert into Employee (Emp_Id,firstName,lastName,salary,Dep_Id,Code) values (5,'ali' , 'geh' , 1200 , (select DepId from Department where Dep_Name = 'CS'),(select code from address where street = 'AAE'));
insert into contact_info values ('john#gmail.com',0785602200, (select Emp_Id from Employee where salary = 1000));
insert into contact_info values ('mark#gmail.com',0785602201, (select Emp_Id from Employee where salary = 2000));
insert into contact_info values ('ahmad#gmail.com',0785602202, (select Emp_Id from Employee where salary = 1100));
insert into contact_info values ('maher#gmail.com',0785602203, (select Emp_Id from Employee where salary = 1700));
insert into contact_info values ('ali#gmail.com',0785602204, (select Emp_Id from Employee where salary = 1200));
-- trigger :
CREATE VIEW vw_address1 AS
SELECT
code,
city,
street
FROM
address;
CREATE OR REPLACE TRIGGER new_trg2
INSTEAD OF INSERT ON vw_address1
FOR EACH ROW
DECLARE
l_code NUMBER;
BEGIN
-- insert a new address first
INSERT INTO address(code,city, street)
VALUES(:NEW.code,:NEW.city, :NEW.street)
RETURNING code INTO l_code;
END;
insert into vw_address1(code,city,street) values (2,'Amman','AAB');

Why is the table view not coming?

I am new to Oracle. The Oracle live SQL shorthand gave ready-made code on the departments and employees model.
I don't understand why the code is not viewing any table although I wrote a select statement. I don't understand the execution protocol.
link
create table departments (
name varchar2(255) not null,
location varchar2(4000),
country varchar2(4000)
)
;
create table employees (
department_id number
constraint employees_department_id_fk
references departments on delete cascade,
name varchar2(50) not null,
email varchar2(255),
cost_center number,
date_hired date,
job varchar2(255)
)
;
insert into departments (
name,
location,
country
) values (
'Security',
'Tanquecitos',
'United States'
);
insert into departments (
name,
location,
country
) values (
'Travel',
'Sugarloaf',
'United States'
);
insert into departments (
name,
location,
country
) values (
'Office of the CEO',
'Dale City',
'United States'
);
insert into departments (
name,
location,
country
) values (
'Security',
'Grosvenor',
'United States'
);
commit;
-- load data
insert into employees (
department_id,
name,
email,
cost_center,
date_hired,
job
) values (
1,
'Gricelda Luebbers',
'gricelda.luebbers#aaab.com',
20,
sysdate - 94,
'Systems Designer'
);
insert into employees (
department_id,
name,
email,
cost_center,
date_hired,
job
) values (
1,
'Dean Bollich',
'dean.bollich#aaac.com',
11,
sysdate - 74,
'Legal Assistant'
);
insert into employees (
department_id,
name,
email,
cost_center,
date_hired,
job
) values (
1,
'Milo Manoni',
'milo.manoni#aaad.com',
21,
sysdate - 68,
'Systems Designer'
);
insert into employees (
department_id,
name,
email,
cost_center,
date_hired,
job
) values (
1,
'Laurice Karl',
'laurice.karl#aaae.com',
78,
sysdate - 73,
'Programmer'
);
select
departments.name department_name,
departments.location location,
departments.country country,
employees.name employee_name,
employees.email email,
employees.cost_center cost_center,
employees.date_hired date_hired,
employees.job job
from
departments,
employees;
This is the output they are showing after running:
Table created.
ORA-02268: referenced table does not have a primary key
1 row(s) inserted.
1 row(s) inserted.
1 row(s) inserted.
1 row(s) inserted.
Statement processed.
ORA-00942: table or view does not exist
ORA-00942: table or view does not exist
ORA-00942: table or view does not exist
ORA-00942: table or view does not exist
ORA-00942: table or view does not exist
Your table departments does not have a primary key, so the constraint in table employees produces an error, and the table employees is not created.
You should refactor your SQL code, adding a proper primary key to the table involved and manage the insert value properly:
create table departments (
id numeric(10) not null
name varchar2(255) not null,
location varchar2(4000),
country varchar2(4000),
CONSTRAINT id PRIMARY KEY (id)
)
;

How to solve single-row subquery returns more than one row

I have an employee table and it contains salary table. I want to give %10 increase to all current employees. I tried to update all employees' salary dates to specific date but I encountered problem with single-row subquery.
My database like this:
CREATE TYPE TEMPORAL_VARCHAR AS OBJECT (
VALID_TIME_LOWER_BOUND DATE,
VALID_TIME_UPPER_BOUND DATE,
VALUE_PART VARCHAR2(50) );
CREATE TYPE TEMPORAL_NUMBER AS OBJECT (
VALID_TIME_LOWER_BOUND DATE,
VALID_TIME_UPPER_BOUND DATE,
VALUE_PART NUMBER );
CREATE TYPE NAME_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE ADDRESS_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE DEPARTMENT_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE MANAGER_TYPE AS TABLE OF TEMPORAL_VARCHAR;
CREATE TYPE SALARY_TYPE AS TABLE OF TEMPORAL_NUMBER;
CREATE TABLE EMPLOYEE (
SSN NUMBER primary key,
NAME NAME_TYPE,
ADDRESS ADDRESS_TYPE ,
BIRTH_DATE DATE,
MANAGER MANAGER_TYPE ,
DEPARTMENT DEPARTMENT_TYPE,
SALARY SALARY_TYPE
)
NESTED TABLE NAME STORE AS NAME_TABLE,
NESTED TABLE ADDRESS STORE AS ADDRESS_TABLE,
NESTED TABLE MANAGER STORE AS MANAGER_TABLE,
NESTED TABLE DEPARTMENT STORE AS DEPARTMENT_TABLE,
NESTED TABLE SALARY STORE AS SALARY_TABLE
;
How to solve this problem? I tried to do this
UPDATE TABLE(
SELECT E.SALARY
FROM EMPLOYEE E
) SAL
SET SAL.VALID_TIME_UPPER_BOUND = '11.16.2015'
WHERE SAL.VALID_TIME_UPPER_BOUND = TO_DATE('12.31.9999','MM.DD.YYYY');
1st it can be duplicate
2nd see sample here
3rd in your code you need bring the where condition into select
UPDATE TABLE(
SELECT E.SALARY
FROM EMPLOYEE E
WHERE ssn in (SELECT ssn FROM EMPLOYEE e
WHERE to_date('01.01.2015','mm.dd.yyyy') in (
SELECT VALID_TIME_UPPER_BOUND FROM TABLE(e.salary)
)
)
) SAL
SET SAL.VALID_TIME_UPPER_BOUND = to_date('01.01.9999','mm.dd.yyyy')
test data
INSERT INTO EMPLOYEE(SSN, salary) values (1, SALARY_TYPE ());
INSERT INTO EMPLOYEE(SSN, salary) values (2, SALARY_TYPE ());
INSERT INTO EMPLOYEE(SSN, salary) values (3, SALARY_TYPE ());
INSERT INTO TABLE(SELECT salary FROM EMPLOYEE
WHERE ssn = 1)
VALUES (to_date('01.01.2005','mm.dd.yyyy'), to_date('01.01.2015','mm.dd.yyyy'), 1);
INSERT INTO TABLE(SELECT salary FROM EMPLOYEE
WHERE ssn = 2)
VALUES (to_date('02.02.2005','mm.dd.yyyy'), to_date('02.02.2015','mm.dd.yyyy'), 2);
INSERT INTO TABLE(SELECT salary FROM EMPLOYEE
WHERE ssn = 3)
VALUES (to_date('03.03.2005','mm.dd.yyyy'), to_date('03.03.2015','mm.dd.yyyy'), 3);
p.s do you really need the complexity?
I solved my problem using iteration like this
BEGIN
FOR employees IN (SELECT SSN FROM EMPLOYEE)
LOOP
UPDATE TABLE(
SELECT E.SALARY
FROM EMPLOYEE E
WHERE E.SSN = employees.SSN
) SAL
SET SAL.VALID_TIME_UPPER_BOUND = '11.16.2015'
WHERE SAL.VALID_TIME_UPPER_BOUND = TO_DATE('12.31.9999','MM.DD.YYYY');
END LOOP;
END;

Insert values of one table in a database to another table in another database

I would like to take some data from a table from DB1 and insert some of that data to a table in DB2.
How would one proceed to do this?
This is what I've got so far:
CREATE VIEW old_study AS
SELECT *
FROM dblink('dbname=mydb', 'select name,begins,ends from study')
AS t1(name varchar(50), register_start date, register_end date);
/*old_study now contains the data I wanna transfer*/
INSERT INTO studies VALUES (nextval('studiesSequence'),name, '',3, 0, register_start, register_end)
SELECT name, register_start, register_end from old_study;
This is how my table in DB2 looks:
CREATE TABLE studies(
id int8 PRIMARY KEY NOT NULL,
name_string VARCHAR(255) NOT NULL,
description VARCHAR(255),
field int8 REFERENCES options_table(id) NOT NULL,
is_active INTEGER NOT NULL,
register_start DATE NOT NULL,
register_end DATE NOT NULL
);
You should include the column names in both the insert and select:
insert into vip_employees(name, age, occupation)
select name, age, occupation
from employees;
However, your data structure is suspect. Either you should use a flag in employees to identify the "VIP employees". Or you should have a primary key in employees and use this primary key in vip_employees to refer to employees. Copying over the data fields is rarely the right thing to do, especially for columns such as age which are going to change over time. Speaking of that, you normally derive age from the date of birth, rather than storing it directly in a table.
INSERT INTO studies
(
id
,name_string
,description
,field
,is_active
,register_start
,register_end
)
SELECT nextval('studiesSequence')
,NAME
,''
,3
,0
,register_start
,register_end
FROM dblink('dbname=mydb', 'select name,begins,ends from study')
AS t1(NAME VARCHAR(50), register_start DATE, register_end DATE);
You can directly insert values that retured by dblink()(that means no need to create a view)
Loop and cursor are weapons of last resort. Try to avoid them. You probably want INSERT INTO ... SELECT:
INSERT INTO x(x, y, z)
SELECT x, y, z
FROM t;
SqlFiddleDemo
EDIT:
INSERT INTO vip_employees(name, age, occupation) -- your column list may vary
SELECT name, age, occupation
FROM employees;
Your syntax is wrong. You cannot have both, a values clause for constant values and a select clause for a query in your INSERT statement.
You'd have to select constant values in your query:
insert into studies
(
id,
name_string,
description,
field,
is_active,
register_start,
register_end
)
select
studiesSequence.nextval,
name,
'Test',
null,
0,
register_start,
register_end
from old_study;

SQL Server Management Studio: The multi-part identifier could not be bound

I'm taking a SQL class, and on one of the assignments I am asked to create a table with employees, one with projects, as follows:
create table [EMPLOYEE]
(
EmployeeID int identity(1, 1) primary key not null,
FirstName varchar(15) not null,
LastName varchar(15) not null,
Gender char(1) not null,
DOB date not null,
SSN char(9) not null
)
create table [PROJECT]
(
ProjectID int identity(1, 1) primary key not null,
Manager int not null,
PDescription varchar(50) not null,
PStatus varchar(20) not null,
StartDate date not null,
EndDate date not null
)
Where the Manager is the ID of an EMPLOYEE entity. Basically projects are assigned to employees. So, I add some employees and projects
insert into EMPLOYEE (FirstName, LastName, Gender, DOB, SSN)
values ('Chuck', 'Carter', 'M', '07/14/1990', '444556666')
This is the one employee I'm interested in, and in the inserting I'm doing this is the second one, so its EmployeeID would be 2. As for the projects:
insert into PROJECT (Manager, PDescription, PStatus, StartDate, EndDate)
values (2, 'Submit source code for 3D racing game', 'In progress', '01/05/2015', '03/05/2015')
insert into PROJECT (Manager, PDescription, PStatus, StartDate, EndDate)
values (2, 'Test videogame for bugs', 'Not started', '03/05/2015', '05/05/2015')
These two are the ones assigned to the employee above, notice Manager for both is 2, and the EmployeeID of Chuck is supposed to be 2. So, I'm supposed to display the employee name as a full name, combining the first and last name, of those who have been assigned two or more projects (in this case, Chuck).
I wrote this code:
select
FirstName + LastName as FullName
from
EMPLOYEE
where
EmployeeID = PROJECT.Manager and count(PROJECT.Manager) >= 2
But instantly I get this error:
The multi-part identifier "PROJECT.Manager" could not be bound.
Am I supposed to make an inner join to recognize the PROJECT table? But I'm only supposed to display the name of the employee. How can I manage to use the PROJECT.manager column values without displaying them?
Thank you very much in advance.
You have to Join Project table, Add Group by with having clause to filter the Manager
select FirstName +' '+ LastName as FullName
from EMPLOYEE
INNER JOIN PROJECT
on EmployeeID = PROJECT.Manager
group by FirstName +' '+ LastName
Having count(PROJECT.Manager) >= 2