问题:
您要临时存储SQL的结果。
解
我们可以使用CREATE GLOBAL TEMPORARY TABLE语句创建一个表,该表临时存储会话的数据。此外,您可以指定是保留会话的临时表数据还是事务提交之前。我们可以进一步使用ON COMMIT PRESERVE ROWS子句来指定在用户会话结束时删除的数据。
CREATE GLOBAL TEMPORARY TABLE tmp_players ON COMMIT PRESERVE ROWS AS SELECT * FROM players WHERE coach_id IS NOT NULL;
全局临时表存储仅在会话期间存在的会话专用数据。一旦我们创建了一个临时表,它就会一直存在,直到我们删除它为止。
select table_name, temporary from user_tables WHERE temporary = 'Y'; TMP_PLAYERS Y
当我们可以在临时表中创建记录时,将在默认的临时表空间中分配空间。我们可以通过运行以下SQL进行验证。
SELECT username, contents, segtype FROM v$sort_usage;
为了提高表的性能,我们可以创建索引并将其放在会话结束时。
最后,我们可以使用ON COMMIT DELETE ROWS子句来指示应在会话结束时删除数据。以下示例对此进行了解释。
CREATE GLOBAL TEMPORARY TABLE tmp_players ON COMMIT DELETE ROWS AS SELECT * FROM players WHERE coach_id IS NOT NULL;
DROP TABLE players; COMMIT; CREATE TABLE players ( player_rank NUMBER(6) , first_name VARCHAR2(20) , last_name VARCHAR2(25) CONSTRAINT player_last_name_nn NOT NULL , email VARCHAR2(30) CONSTRAINT player_email_nn NOT NULL , phone_number VARCHAR2(20) , player_start_date DATE CONSTRAINT player_start_date_nn NOT NULL , title_id VARCHAR2(20) CONSTRAINT player_title NOT NULL , prize_money NUMBER(8,2) , coach_id NUMBER(6) , CONSTRAINT player_email UNIQUE (email) ) ;
INSERT INTO players VALUES (1,'Roger','Federer','roger.federer@notreal.com','111.111.1234',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'AUS_OPEN','350000',1); INSERT INTO players VALUES (2,'Rafa','Nadal','Rafa.Nadal@notreal.com','111.111.1235',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',1); INSERT INTO players VALUES (3,'Andy','Murray','Andy.Murray@notreal.com','111.111.1236',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'WIMBELDON','450000',1); INSERT INTO players VALUES (4,'Stan','Wawrinka','Stan.Wawrinka@notreal.com','111.111.1237',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',2); INSERT INTO players VALUES (5,'Dominic','Theim','Dominic.Theim@notreal.com','111.111.1238',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'US_OPEN','500000',2); INSERT INTO players VALUES (6,'Novak','Djokovic','Novak.Djokovic@notreal.com','111.111.1239',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'AUS_OPEN','350000',2); INSERT INTO players VALUES (7,'Andy','Zverev','Andy.Zverev@notreal.com','111.111.1240',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',2); INSERT INTO players VALUES (8,'Andy','Rublev','Andy.Rublev@notreal.com','111.111.1241',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'WIMBELDON','450000',3); INSERT INTO players VALUES (9,'Janik','Sinner','Janik.Sinner@notreal.com','111.111.1242',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',3); INSERT INTO players VALUES (10,'Danil','Medvedev','Danil.Medvedev@notreal.com','111.111.1243',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'US_OPEN','500000',3); COMMIT;