PL/SQL 立即执行创建 table 并向其中插入数据

PL/SQL Execute immediate create table and insert data into it

让我们看看我的源代码:

CREATE OR REPLACE PROCEDURE MAKE_COPY_OF_CLASSROOMS AUTHID CURRENT_USER AS

TYPE classrooms_table_type IS TABLE OF classrooms%ROWTYPE INDEX BY PLS_INTEGER;
classrooms_backup classrooms_table_type;

CURSOR classrooms_cursor IS
SELECT *
FROM classrooms
WHERE year = 1
ORDER BY name;

v_rowcnt PLS_INTEGER := 0;

BEGIN
    OPEN classrooms_cursor;
        FETCH classrooms_cursor
         BULK COLLECT INTO classrooms_backup;
    CLOSE classrooms_cursor;    

    EXECUTE IMMEDIATE 'CREATE TABLE classrooms_copy AS (SELECT * FROM classrooms WHERE 1 = 2)';
--COPY ALL STORED DATA FROM classrooms_backup TO classrooms_copy

END MAKE_COPY_OF_classrooms;

我在尝试将数据从 "classrooms_backup" 插入 table "classrooms_copy" 时被困了几个小时,这是由 EXECUTE IMMEDIATE 命令创建的。有必要通过 EXECUTE IMMEDIATE 命令创建 table "classrooms_copy"。我试图创建另一个带有 for 循环的 EXECUTE 命令:

EXECUTE IMMEDIATE 'FOR i IN classrooms_backup.FIRST..classrooms_backup.LAST LOOP
  INSERT INTO classrooms_copy(id,room_id,year,name) 
  VALUES(classrooms_backup(i).id,classrooms_backup(i).room_id,classrooms_backup(i).year,classrooms_backup(i).name);
  END LOOP;';

但这是通往地狱的道路。我正在检索无效的 SQL 语句错误。 感谢您的帮助!

这里不需要太多PL/SQL。另外,请尽量避免使用关键字 CURSOR - 几乎总有更好的方法。

create or replace procedure make_copy_of_classrooms authid current_user as
begin
    execute immediate '
        create table classrooms_copy as
        select *
        from classrooms
        where year = 1
        order by name
    ';
end make_copy_of_classrooms;
/