oracle 使用 FETCH 的 PL/SQL Cursor FOR 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29760570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PL/SQL Cursor FOR loop using FETCH
提问by Joe Boris
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. Fetch and process each record and insert a row in the table log for each blog id returned.
如果博客 id 小于 4,则使用游标 FOR 循环检索博客 id、博客 url 和博客描述,并将其放置在游标变量中。获取并处理每条记录,并为返回的每个博客 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. The question seems poorly written but how would you answer it using the FETCH keyword? I'm new to PL/SQL but I have experience with SQL.
查询完成了这项工作,但它不使用 FETCH 关键字,因此我们认为它在技术上不正确。这个问题似乎写得不好,但是您将如何使用 FETCH 关键字回答它?我是 PL/SQL 的新手,但我有 SQL 的经验。
回答by null
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;