我正在阅读很多关于在循环中重复Select语句的东西,但是我遇到了一些困难,因为到目前为止还没有找到清楚的东西。我想多次执行一些查询(选择查询),就像在FOR循环中一样。请问有人可以帮忙吗?
答案 0 :(得分:8)
您要问的基本结构如下所示。 有关更具体的代码示例,请提供更多信息。
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;