7

我正在阅读很多关于在循环中重复 Select 语句的内容,但我遇到了一些困难,因为到目前为止我还没有找到清楚的东西。我想多次执行一些查询(选择查询),例如在 FOR 循环中。有人可以帮忙举个例子吗?

4

1 回答 1

13

您所问的基本结构如下所示。请提供更多信息以获取更具体的代码示例。

DECLARE
  l_output NUMBER;
BEGIN
  FOR i IN 1..10 LOOP
    SELECT 1
    INTO l_output
    FROM dual;
    DBMS_OUTPUT.PUT_LINE('Result: ' || l_output);
  END LOOP;
END;

PS:如果您需要在 SQL*Plus 中启用输出,您可能需要运行命令
SET SERVEROUTPUT ON

更新

要将结果插入另一个表:

DECLARE
-- Store the SELECT query in a cursor
  CURSOR l_cur IS SELECT SYSDATE DT FROM DUAL;  
--Create a variable that will hold each result from the cursor
  l_cur_rec l_cur%ROWTYPE;
BEGIN
  -- Open the Cursor so that we may retrieve results
  OPEN l_cur;  
  LOOP
    -- Get a result from the SELECT query and store it in the variable
    FETCH l_cur INTO l_cur_rec;
    -- EXIT the loop if there are no more results
    EXIT WHEN l_cur%NOTFOUND;
    -- INSERT INTO another table that has the same structure as your results
    INSERT INTO a_table VALUES l_cur_rec;        
  END LOOP;
  -- Close the cursor to release the memory
  CLOSE l_cur;
END;

要创建结果视图,请参见以下示例:

CREATE VIEW scott.my_view AS 
  SELECT * FROM scott.emp;

要使用视图查看结果:

SELECT * FROM scott.my_view;
于 2013-08-06T20:31:43.317 回答