求助,关于触发器
现在有表结构如下:
STATIONID OBSTIME INSERTTIME RAINFALL RAINFALLM10
12013/7/1 0:01:002013/7/1 0:05:001.00
22013/7/1 0:02:002013/7/1 0:05:002.00
32013/7/1 0:03:002013/7/1 0:05:003.00
.
.
.
stationid 和 obstime 是联合主键pk_rf1,现需要写一个触发器在本表插入新数据的时候,根据stationid和obstime自动累加过去十分钟rainfall的值并插入rainfallm10,自己写了一个触发器,可是不行,来求助各位,谢谢了!
我自己在网上到处搜,然后拼凑的,错在什么地方?怎么解决?
create or replace trigger aifer_rf1
before update
of obstime
on rf1 for each row
begin
execute immediate
'update rf1 set :new.rainfallm10=(
select sum(rainfall) from rf1 t2 where t2.obstime between rf1.obstime-9/1440 and rf1.obstime and rf1.stationid=t2.stationid and :new.pk_rf1 = :old.pk_rf1
)';
end;
[解决办法]
create or replace trigger aifer_rf1
before update
of obstime
on rf1 for each row
begin
:new.rainfallm10 := (
select sum(rainfall) from rf1 t2
where t2.obstime between :new.obstime-1/144 and :new.obstime
and t2.stationid=:new.stationid
)
end;
--不知道楼主需要跟新的到底是那些数据
--以上是跟新本条记录的
--ps:1/144才是10分钟
SQL> CREATE TABLE rf1(stationid number, obstime date, inserttime date, rainfall number, rainfall10 number);
Table created
SQL> insert into rf1 values(1,to_date('20130701 00:01:00','yyyymmdd HH24:MI:SS'), sysdate, 1, 0);
1 row inserted
SQL> insert into rf1 values(1,to_date('20130701 00:02:00','yyyymmdd HH24:MI:SS'), sysdate, 1, 0);
1 row inserted
SQL> create or replace trigger aifer_rf1
2 before insert
3 on rf1 for each row
4 begin
5 select sum(rainfall) into :new.rainfall10 from rf1 t2
6 where t2.obstime between :new.obstime-9/1440 and :new.obstime
7 and t2.stationid=:new.stationid
8 ;
9 end;
10 /
Trigger created
SQL> insert into rf1 values(1,to_date('20130701 00:03:00','yyyymmdd HH24:MI:SS'), sysdate, 1, 0);
1 row inserted
SQL> select * from rf1;
STATIONID OBSTIME INSERTTIME RAINFALL RAINFALL10
---------- ----------- ----------- ---------- ----------
1 7/1/2013 12 12/19/2013 1 0
1 7/1/2013 12 12/19/2013 1 0
1 7/1/2013 12 12/19/2013 1 2
SQL> drop table rf1;
Table dropped
SQL>
create or replace trigger aifer_rf1
before insert on rf1 for each row
begin
:new.rainfallm10 := (
select sum(rainfall) from rf1 t2
where t2.obstime between :new.obstime-1/144 and :new.obstime
and t2.stationid=:new.stationid
)
end;
这个03秒的数据加上去,不应该是3吗?加出来2不对啊
是2,只累加相同stationid的,现在的问题是,如果新插入数据的stationid是之前没有的,rainfallm10就是空值,而需要的是将rainfall的值插入rainfallm10中,不知道表达清楚了没,谢谢
CREATE OR REPLACE TRIGGER aifer_rf1
BEFORE INSERT ON rf1
FOR EACH ROW
BEGIN
SELECT SUM(rainfall)
INTO :new.rainfall10
FROM rf1 t2
WHERE t2.obstime BETWEEN :new.obstime - 9 / 1440 AND :new.obstime
AND t2.stationid = :new.stationid;
:new.rainfall10 := nvl(:new.rainfall10, 0) + nvl(:new.rainfall, 0);
END;
/