简单任务
variable dept_id NUMBER
DECLARE
max_deptno NUMBER;
dept_name departments.department_name%TYPE := 'Education';
BEGIN
select max(department_id)
into max_deptno
from departments;
:dept_id := max_deptno + 10;
insert into departments (department_id, department_name, location_id)
values (:dept_id, dept_name, null);
DBMS_OUTPUT.PUT_LINE('The maximum department id is ' || max_deptno);
DBMS_OUTPUT.PUT_LINE('Rows made by insert: ' || SQL%ROWCOUNT);
END;
max_deptno不是NULL。为什么dept_id在赋值后为NULL?我做错了什么?
脚本输出:
MAX(DEPARTMENT_ID)
------------------
520
Error starting at line 10 in command:
DECLARE
max_deptno NUMBER;
dept_name departments.department_name%TYPE := 'Education1';
BEGIN
select max(department_id)
into max_deptno
from departments;
:dept_id := max_deptno + 10;
insert into departments (department_id, department_name, location_id)
values (:dept_id, dept_name, null);
DBMS_OUTPUT.PUT_LINE('The maximum department id is ' || max_deptno);
DBMS_OUTPUT.PUT_LINE('Rows made by insert: ' || SQL%ROWCOUNT);
END;
错误报告:
ORA-01400: невозможно вставить NULL в ("ANDKOM"."DEPARTMENTS"."DEPARTMENT_ID")
ORA-06512: на line 9
01400. 00000 - "cannot insert NULL into (%s)"
*Cause:
*Action:
答案 0 :(得分:6)
分配后,宿主变量DEPT_ID
不为NULL。问题是您的INSERT
语句正在使用NEW_DPT
中的局部变量INSERT
,并且该局部变量尚未赋值。如果你真的想在PL / SQL中使用主机变量(在现实生活中你基本上不会这样做),你需要在PL / SQL块中使用它?
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 max_deptno NUMBER;
3 new_dpt NUMBER;
4 dept_name departments.department_name%TYPE := 'Education';
5 BEGIN
6 select max(department_id)
7 into max_deptno
8 from departments;
9 :dept_id := max_deptno + 10;
10 insert into departments (department_id, department_name, location_id)
11 values (:dept_id, dept_name, null);
12 DBMS_OUTPUT.PUT_LINE('The maximum department id is ' || max_deptno);
13 DBMS_OUTPUT.PUT_LINE('Rows made by insert: ' || SQL%ROWCOUNT);
14* END;
SQL> /
The maximum department id is 270
Rows made by insert: 1
PL/SQL procedure successfully completed.
SQL> select :dept_id from dual;
:DEPT_ID
----------
280
然而,更现实的是,完全抛弃替代变量
SQL> ed
Wrote file afiedt.buf
1 DECLARE
2 max_deptno NUMBER;
3 new_dpt NUMBER;
4 dept_name departments.department_name%TYPE := 'Education';
5 BEGIN
6 select max(department_id)
7 into max_deptno
8 from departments;
9 new_dpt := max_deptno + 10;
10 insert into departments (department_id, department_name, location_id)
11 values (new_dpt, dept_name, null);
12 DBMS_OUTPUT.PUT_LINE('The maximum department id is ' || max_deptno);
13 DBMS_OUTPUT.PUT_LINE('Rows made by insert: ' || SQL%ROWCOUNT);
14* END;
SQL> /
The maximum department id is 280
Rows made by insert: 1
PL/SQL procedure successfully completed.
答案 1 :(得分:0)
我在oracle论坛上问了同样的问题并得到了答案:
您好,
这是一个已知问题,并且依赖于从未发生的JDBC错误 已经解决: https://forums.oracle.com/forums/thread.jspa?messageID=9456891�
如果您的特定情况不适合设置绑定变量 在一个匿名块中,在另一个中读取它,然后是唯一的 解决方法(也被认为是良好的编码实践)是 用PL / SQL变量替换SQL * Plus变量。
问候,Gary SQL开发团队