如何重复Oracle中循环中的Select语句?

Noa*_*tin 4 sql oracle plsql loops

我正在阅读很多关于在循环中重复Select语句的东西,但是我遇到了一些困难,因为到目前为止我还没有找到清楚的东西.我想多次执行一些查询(选择查询),就像在FOR循环中一样.请问有人可以帮忙吗?

Yia*_*nes 9

您要问的基本结构如下所示.有关更具体的代码示例,请提供更多信息.

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;
Run Code Online (Sandbox Code Playgroud)

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

UPDATE

要将结果插入另一个表:

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;
Run Code Online (Sandbox Code Playgroud)

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

CREATE VIEW scott.my_view AS 
  SELECT * FROM scott.emp;
Run Code Online (Sandbox Code Playgroud)

要使用视图查看结果:

SELECT * FROM scott.my_view;
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,请参阅我的最新回复.这是你需要的吗? (2认同)
  • 我在回复中添加了一些代码,这是否可以解决您的问题? (2认同)