[英]How to use dynamic insert and check on a loop under cursors in pl/sql?
create or replace package IR is
procedure chkval;
end IR;
create or replace package body IR is
procedure chkval is
lheat IR_SENSE.heat%type;
cursor cur is select heat from IR_SENSE;
begin
open cur;
loop
insert into IR_SENSE values(to_number(substr(dbms_random.random,1,4)));
fetch cur into lheat;
dbms_output.put_line(lheat);
commit;
exit when lheat>4000;
exit when cur%notfound;
end loop;
close cur;
end;
end IR`enter code here`
在这里,我试图在表中执行动态插入(值是作为温度从红外传感器发出的),并且如果值超过阈值,则需要发出警报(退出程序)。
这是一个选择; 我没有写程序包(也没有存储过程)-这是一个匿名的PL / SQL块,您可以轻松地将其重写为所需的任何内容。
创建测试用例:
SQL> create table ir_sense (heat number);
Table created.
SQL> insert into ir_sense (heat)
2 select round(dbms_random.value * 7500)
3 from dual
4 connect by level <= 1000;
1000 rows created.
SQL>
代码及其输出:
SQL> set serveroutput on
SQL>
SQL> declare
2 l_treshold number := 8000;
3 l_cnt number := 0; -- number of values lower than L_TRESHOLD
4 begin
5 for cur_r in (select heat from ir_sense
6 order by heat -- so that I wouldn't exit too fast
7 )
8 loop
9 l_cnt := l_cnt + 1;
10 if cur_r.heat > 4000 then
11 dbms_output.put_line('Treshold reached after ' || l_cnt || ' readings');
12 exit;
13 end if;
14 end loop;
15 end;
16 /
Treshold reached after 525 readings
PL/SQL procedure successfully completed.
SQL>
[编辑:一种新方法]
如果值小于4000,则P_SENSE过程将插入值,然后将“ N”作为“ PAR_STOP”参数返回(即“不停止加载”); 否则,返回“ Y”。
SQL> create table ir_sense (heat number);
Table created.
SQL> create or replace procedure p_sense (par_heat in number, par_stop out varchar2) is
2 begin
3 if par_heat > 4000 then
4 -- stop loading
5 par_stop := 'Y';
6 else
7 insert into ir_sense(heat) values (par_heat);
8 par_stop := 'N';
9 end if;
10 end;
11 /
Procedure created.
测试:WHILE循环模拟您从设备接收的值,并一直执行该操作,直到P_SENSE过程返回PAR_STOP = Y(即停止加载)。
SQL> declare
2 l_heat number;
3 l_stop varchar2(1) := 'N';
4 begin
5 -- simulating temperature readings
6 while l_stop = 'N' loop
7 l_heat := round(dbms_random.value * 7500);
8 p_sense(l_heat, l_stop);
9 end loop;
10 end;
11 /
PL/SQL procedure successfully completed.
SQL> select count(*) from ir_sense;
COUNT(*)
----------
3
SQL> select * from ir_sense;
HEAT
----------
187
2328
1072
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.