我正在尝试将值插入Oracle SQL中的“Employee”表。我有一个关于输入由外键确定的值的问题:
我的员工有3个由外键决定的属性:State,Position,&经理。我使用INSERT INTO
语句来插入值并手动输入数据。我是否需要在物理上查找每个引用以输入数据,或者是否有可以使用的命令?例如。
INSERT INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
VALUES
(001, "John Doe", "1 River Walk, Green Street", 3, 5, 1000)
这应该使用(John Doe, 1 River Walk, Green Street, New York, Sales Executive, Barry Green)
填充employee表。 state_id=3
表中的纽约是State
; position_id=5
表中的销售主管为positions
;和Barry Green在manager_id=1000
表格中manager
。
有没有办法可以输入引用表的文本值,以便Oracle识别文本并将其与相关ID匹配?我希望这个问题有意义,很乐意澄清任何事情。
谢谢!
答案 0 :(得分:9)
您可以使用以下功能,以便在插入之前从DB中提取更多参数:
--
-- insert_employee (Function)
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2)
RETURN VARCHAR2 AS
p_state_id varchar2(30) := '';
BEGIN
select state_id
into p_state_id
from states where lower(emp_state) = state_name;
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES
(p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);
return 'SUCCESS';
EXCEPTION
WHEN others THEN
RETURN 'FAIL';
END;
/
答案 1 :(得分:7)
INSERT
INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM dual
JOIN state s
ON s.state_name = 'New York'
JOIN positions p
ON p.position_name = 'Sales Executive'
JOIN manager m
ON m.manager_name = 'Barry Green'
请注意,但是单个拼写错误(或额外空格)将导致不匹配,并且不会插入任何内容。
答案 2 :(得分:4)
您可以从SELECT中插入表格。
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
(SELECT id FROM state WHERE name = 'New York'),
(SELECT id FROM positions WHERE name = 'Sales Executive'),
(SELECT id FROM manager WHERE name = 'Barry Green')
FROM
dual
或者,同样......
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
state.id,
positions.id,
manager.id
FROM
state
CROSS JOIN
positions
CROSS JOIN
manager
WHERE
state.name = 'New York'
AND positions.name = 'Sales Executive'
AND manager.name = 'Barry Green'
虽然这个确实假设所有的查找都存在。例如,如果没有位置名称“Sales Executive”,则此版本不会插入任何内容。