循环访问游标的数据并比较另一个表的值sql

时间:2016-09-07 19:39:47

标签: sql database oracle toad

我有两张桌子。我想按照以下步骤从表2中得到desc:
1.从Table1中选择名称,其中type =' animal';
2.遍历每个名​​称1.并检查表2,即o_name = name;
3.然后检查该o_name是否存在desc 4.如果desc不存在,那么插入宠物'表2中的记录。

我该怎么办?现在我有一个名为Table1的游标。我正在考虑循环使用光标的记录,但除此之外,我无法做到。请建议我:

DECLARE
    CURSOR DATA is
        SELECT name 
        FROM Table1
        where type='animal';    
BEGIN
     FOR C IN DATA LOOP
        // After this what can I do?? I cannot do select into because there will be
        // multiple rows
     END LOOP;   
END;

/

Table1:
id | name  | type
---| ----  | -----
  1| Apple | food
  2| Ball  | game
  3| Cat   | animal
  4| Cow   | animal
  5| Ball  | game

   Table2:
o_name | desc
    ---| ----
  Apple| eat  
    Cat| pet
    Cow|  

1 个答案:

答案 0 :(得分:1)

您仍然可以执行此操作作为查询而不需要游标。请注意,数据库已针对处理记录集进行了优化,这就是SQL查询的作用。只有在其他策略不起作用时才应使用游标。

UPDATE Table2
SET "desc" = 'pet'
WHERE
    "desc" IS NULL AND
    o_name IN (SELECT name FROM Table1 WHERE "type" = 'animal')

请注意,DESCTYPEreserved words in Oracle,因此我将其用双引号括起来。单引号用于在Oracle中包含文本文字(字符串)。