在嵌套循环中执行立即语句不适用于PL / SQL

时间:2014-03-19 02:08:26

标签: sql dynamic plsql

create or replace procedure NN(k number) as

cursor cursor1 IS 
select id,x,y from query_points;

cursor cursor2 IS
select x,y from data_points;

sid number;

x1 number;
y1 number;

x2 number;
y2 number;

dist number;
result number;

begin
open cursor1;

loop
    execute immediate 'delete from temp';
    fetch cursor1 into sid, x1, y1;

    exit when cursor1%notfound;


    for rec in (select x,y from data_points) loop
        x2 := rec.x;
        y2 := rec.y;

        dist:= sqrt(((x2-x1)**2)+((y2-y1)**2)); 

        execute immediate 'insert into temp values('||dist||')';    
    end loop;
    select distance into result from temp where rownum=k order by distance;
    execute immediate 'insert into nn_results values('||sid||','||k||','||result||')';
end loop;

close cursor1;
end;

此过程中的动态sql语句在循环中不执行,而是单独执行。

此外,该程序不会终止。它会导致谷歌浏览器崩溃。

有经验的人吗?

1 个答案:

答案 0 :(得分:0)

在这种情况下,

EXECUTE IMMEDIATE不是必需的。试一试:

create or replace procedure NN(k number) as
  dist number;
  result number;
begin
  for aRow IN (select id,x,y from query_points)
  loop
    delete from temp;

    for rec in (select x,y from data_points)
    loop
      dist:= sqrt(((rec.X-aRow.X)**2)+((rec.Y-aRow.Y)**2)); 

      insert into temp values(dist);
    end loop;

    SELECT DISTANCE
      into result
      FROM (select distance, ROWNUM as RNUM
              from temp
              order by distance)
      where rnum = k;

    insert into nn_results values(aRow.ID, k, result);
  end loop;
end NN;

使用游标FOR循环和行变量可以大大简化代码。

分享并享受。