我正在使用PL / SQL Developer。
我尝试更新列(现有表)中的值。 用于填充行的值应自动递增。起始值是此类字段中已存在的最大值。
一个例子,我有下表
ORDER_ID T_NAME T_PRICE
20 CAR 50
NULL VAN 100
NULL BIKE 10
NULL BOAT 300
运行查询后,我希望该表看起来像:
ORDER_ID T_NAME T_PRICE
20 CAR 50
21 VAN 100
22 BIKE 10
23 BOAT 300
到目前为止我创建的查询是:
DECLARE
temp_order_id number;
BEGIN
:temp_order_id = SELECT ISNULL(MAX((ORDER_ID)),0) + 1 FROM SALES_ACC;
update SALES_ACC
set (ORDER_ID) = :temp_order_id , :temp_order_id = :temp_order_id + 1
where (ORDER_ID) is null;
END;
Oracle不喜欢将select语句中的值赋给temp_order_id变量。
有没有人知道如何修复它?
答案 0 :(得分:4)
你不需要pl / sql - 你可以在一个更新语句中完成 - 例如:
create table test1 as
select 20 order_id, 'CAR' t_name, 50 t_price from dual union all
select null order_id, 'VAN' t_name, 100 t_price from dual union all
select null order_id, 'BIKE' t_name, 10 t_price from dual union all
select null order_id, 'BOAT' t_name, 300 t_price from dual;
update test1
set order_id = (select max(order_id) from test1) + rownum
where order_id is null;
commit;
select * from test1
order by 1;
ORDER_ID T_NAME T_PRICE
---------- ------ ----------
20 CAR 50
21 VAN 100
22 BIKE 10
23 BOAT 300
drop table test1;
作为旁注,听起来像order_id应该是表格的主键 - 如果你有,那么就不允许你添加没有值的行。另外,您还需要一个序列,然后在将数据插入表格时使用 - 例如:
insert into test1 (order_id, t_name, t_price)
values (test1_seq.nextval, 'TRIKE', 30);
答案 1 :(得分:2)
ORACLE推荐的方式是:
参见How to create id with AUTO_INCREMENT on Oracle?,这里描述了两种方法。
答案 2 :(得分:1)
在DECLARE ... BEGIN ... END;
部分中,您使用的是PL / SQL语法。这不等于SQL语法。在PL / SQL语法中,您应该使用所谓的select into
语句。
SELECT ISNULL(MAX((ORDER_ID)),0) + 1
into :temp_order_id
FROM SALES_ACC