如何使用动态插入并检查pl / sql中游标下的循环?

时间:2018-03-26 15:16:07

标签: sql plsql

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`

在这里,我试图在表格中执行动态插入(值来自IR传感器作为临时值),如果值超过阈值,我需要发出警报(退出程序)。

1 个答案:

答案 0 :(得分:0)

这是一个选项;我没有写一个包(也没有存储过程) - 这是一个匿名的PL / SQL块,您可以轻松地将其重写为您想要的任何内容。

创建测试用例:

foreach(var row in targetDataRows)
{
     var startDate = (DateTime)row["startdate"];
     var endDate = (DateTime)row["enddate"];
     var nonMatchingRows = (from row in overallDataTable.AsEnumerable()
                            where !targetIds.Contains(row.Field<int>("ID")) && DateTime.Compare(row.Field<DateTime>("startdate"), startDate) == 0 && DateTime.Compare(row.Field<DateTime>("enddate"), endDate) == 0
                            select row).ToList();
     foreach(var nonMatchingRow in nonMatchingRows)
     {
           overallDataTable.Tables[0].Rows.Remove(nonMatchingRow);
     }
}

代码&amp;它的输出:

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>

[编辑:新方法]

P_SENSE过程如果它们低于4000则插入值并返回'N'作为“PAR_STOP”参数(即“不停止加载”);否则,它返回“Y”。

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>

测试:WHILE循环模拟您从设备接收的值,并一直这样做,直到P_SENSE过程返回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.