简体   繁体   English

使用FETCH的PL / SQL Cursor FOR循环

[英]PL/SQL Cursor FOR loop using FETCH

I'm trying to help my friend with his Oracle homework and he has the following problem: 我正在尝试帮助我的朋友完成他的Oracle作业,他遇到以下问题:

Use a cursor FOR loop to retrieve the blog id, blog url and blog description if the blog id is less than 4 and place it in a cursor variable. 如果博客ID小于4,则使用游标FOR循环检索博客ID,博客URL和博客描述,并将其放在游标变量中。 Fetch and process each record and insert a row in the table log for each blog id returned. 获取并处理每条记录,并在表日志中为返回的每个博客ID插入一行。

We're finding it hard to understand but we have the query: 我们发现很难理解,但有以下查询:

DECLARE
    CURSOR blog_cursor IS SELECT * FROM blog;
BEGIN
  FOR blog_item IN blog_cursor LOOP
    IF( blog_item.blog_id > 4 ) THEN
      -- Insert a row in the "table log"
      INSERT INTO log( log_id, log_url, log_desc )
      VALUES( blog_item.blog_id, blog_item.blog_url, blog_item.blog_desc );
    END IF;
  END LOOP;
END;
/

Table: 表:

blog
    blog_id
    blog_url
    blog_desc

The query does the job, but it doesn't use the FETCH keyword so we don't think it's technically right. 该查询可以完成工作,但是它不使用FETCH关键字,因此我们认为这在技术上不正确。 The question seems poorly written but how would you answer it using the FETCH keyword? 这个问题似乎写得不好,但是您如何使用FETCH关键字回答呢? I'm new to PL/SQL but I have experience with SQL. 我是PL / SQL的新手,但是我有使用SQL的经验。

You did it right and you don't need a fetch, in fact you did the fetch but you did it implicitly, to use a fetch keyword you need a record type and also you will need to open and close the cursor and also check for is it open or not and also check for if it has rows(in the loop), following is another for of your cursor which uses fetch and a record type: 您做对了,您不需要获取,实际上您进行了获取,但是您暗含了此操作。要使用fetch关键字,您需要一个record类型,并且还需要打开和关闭游标并检查它是否打开,还检查它是否有行(在循环中),以下是使用fetch和记录类型的另一个游标:

DECLARE
    CURSOR blog_cursor IS SELECT * FROM blog;
    blog_item blog%rowtype;
BEGIN
  OPEN blog_cursor;
  LOOP
    FETCH blog_cursor INTO blog_item;
    EXIT WHEN blog_cursor%NOTFOUND;
    IF( blog_item.blog_id > 4 ) THEN
      -- Insert a row in the "table log"
      INSERT INTO log( log_id, log_url, log_desc )
      VALUES( blog_item.blog_id, blog_item.blog_url, blog_item.blog_desc );
    END IF;
  END LOOP;
  CLOSE blog_cursor;
END;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM