循环遍历游标的数据并比较另一个表的sql值
我有两张桌子。我想在完成以下步骤后从表2中获取desc: 1.从表1中选择名称,其中类型='animal'; 2.从1循环每个名称。并检查表2,即o_name=name; 3.然后检查该o_名称是否存在desc。 4.如果描述不存在,则在表2中为该记录插入“pet”循环遍历游标的数据并比较另一个表的sql值,sql,database,oracle,toad,Sql,Database,Oracle,Toad,我有两张桌子。我想在完成以下步骤后从表2中获取desc: 1.从表1中选择名称,其中类型='animal'; 2.从1循环每个名称。并检查表2,即o_name=name; 3.然后检查该o_名称是否存在desc。 4.如果描述不存在,则在表2中为该记录插入“pet” Table1: id | name | type ---| ---- | ----- 1| Apple | food 2| Ball | game 3| Cat | animal 4| Cow | an
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。我正在考虑循环浏览光标的记录,但除此之外,我无法完成。请建议我:
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|
/
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|
您仍然可以作为查询执行此操作,而不需要游标。请注意,数据库是为处理记录集而优化的,SQL查询就是这样做的。只有在其他策略不起作用时才应使用游标
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|
UPDATE Table2
SET "desc" = 'pet'
WHERE
"desc" IS NULL AND
o_name IN (SELECT name FROM Table1 WHERE "type" = 'animal')
请注意,DESC和TYPE是相同的,因此我用双引号将它们括起来。单引号用于将Oracle中的文本文字字符串括起来。为什么要使用光标?@rjdevereux Hi Rj我们可以不用光标吗?为什么需要在表1中循环。大家都知道这个名字将是猫。那么为什么不直接从表2中得到猫呢?目前还不清楚您试图实现的目标。通常您会执行一些操作,如从表1中选择a.id、a.name、b.desc a内部联接表2 b ON a.name=b.o_name,其中a.name='Cat'按a.id、b.desc排序。但正如我之前所说,如果你只需要得到猫,那么使用table1似乎毫无意义,除非你需要它的其他栏。@Olivier我刚刚更新了这个问题。请看一看。
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|