我有这个表:员工(id,名字,姓氏,工资),我添加了另一列,用于存储每位员工过去的所有工资。
CREATE OR REPLACE TYPE salary_list AS TABLE OF NUMBER;
/
ALTER TABLE employees
ADD (salary_history salary_list)
NESTED TABLE salary_history STORE AS salary_history_tab;
现在,该表是员工(id,firstname,lastname,salary, salary_history ),salary_history为null。当我修改salaray值时,如何将当前工资值插入内部表salary_history?我试过:
INSERT INTO
TABLE(SELECT salary_history FROM employees WHERE id=1)
VALUES(1500);
我收到以下错误:
ORA-22908:对NULL表值的引用
是的,嵌套表salary_history为null,因为我刚刚创建它。我究竟做错了什么?将值(附加到现有数据)插入 salary_history 以正确识别员工的正确方法是什么?
更新: 像这样添加了nvl(,()):
INSERT INTO
TABLE(SELECT nvl(salary_history,salary_list()) FROM employees WHERE id=1)
VALUES(1000);
我现在得到的错误是:
ORA-25015:无法在此嵌套表视图列
上执行DML
答案 0 :(得分:3)
您可以使用COALESCE( salary_history, salary_list() ) MULTISET UNION ALL salary_list( :your_new_value )
将新值附加到旧列表中(如果不存在则创建新列表)。
Oracle 11g R2架构设置:
CREATE OR REPLACE TYPE salary_list AS TABLE OF NUMBER;
/
CREATE TABLE employees(
id NUMBER,
salary_history salary_list
) NESTED TABLE salary_history STORE AS salary_history_tab
/
INSERT INTO employees VALUES ( 1, NULL )
/
查询1 :
UPDATE employees
SET salary_history = COALESCE( salary_history, salary_list() )
MULTISET UNION ALL salary_list( 500 )
WHERE id = 1
SELECT * FROM employees
<强> Results 强>:
| ID | SALARY_HISTORY |
|----|----------------|
| 1 | 500 |
查询2 :
UPDATE employees
SET salary_history = COALESCE( salary_history, salary_list() )
MULTISET UNION ALL salary_list( 700 )
WHERE id = 1
SELECT * FROM employees
<强> Results 强>:
| ID | SALARY_HISTORY |
|----|----------------|
| 1 | 500,700 |
查询3 :
UPDATE employees
SET salary_history = COALESCE( salary_history, salary_list() )
MULTISET UNION ALL salary_list( 500 )
WHERE id = 1
SELECT * FROM employees
<强> Results 强>:
| ID | SALARY_HISTORY |
|----|----------------|
| 1 | 500,700,500 |
答案 1 :(得分:2)
该列当前为null,而不是空表;您可以创建一个空的嵌套表来开始:
UPDATE employees
SET salary_history = NEW salary_list()
WHERE id = 1;
1 row updated.
然后你的第一个陈述将起作用:
INSERT INTO
TABLE(SELECT salary_history FROM employees WHERE id=1)
VALUES(1500);
1 row inserted.
您可以看到新值:
SELECT * FROM employees;
ID FIRSTNAME LASTNAME SALARY SALARY_HISTORY
---------- ---------- ---------- ---------- ------------------------------
1 Joe BLoggs 1234 SALARY_LIST(1500)