如何在 Oracle 中临时存储数据以供以后使用?


问题

您想临时存储 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','[email protected]','111.111.1234',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'AUS_OPEN','350000',1);
INSERT INTO players VALUES (2,'Rafa','Nadal','[email protected]','111.111.1235',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',1);
INSERT INTO players VALUES (3,'Andy','Murray','[email protected]','111.111.1236',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'WIMBELDON','450000',1);
INSERT INTO players VALUES (4,'Stan','Wawrinka','[email protected]','111.111.1237',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',2);
INSERT INTO players VALUES (5,'Dominic','Theim','[email protected]','111.111.1238',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'US_OPEN','500000',2);
INSERT INTO players VALUES (6,'Novak','Djokovic','[email protected]','111.111.1239',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'AUS_OPEN','350000',2);
INSERT INTO players VALUES (7,'Andy','Zverev','[email protected]','111.111.1240',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',2);
INSERT INTO players VALUES (8,'Andy','Rublev','[email protected]','111.111.1241',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'WIMBELDON','450000',3);
INSERT INTO players VALUES (9,'Janik','Sinner','[email protected]','111.111.1242',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'FRENCH_OPEN','300000',3);
INSERT INTO players VALUES (10,'Danil','Medvedev','[email protected]','111.111.1243',TO_DATE('17-06-2003', 'dd-MM-yyyy'),'US_OPEN','500000',3);

COMMIT;

更新于: 2020-12-05

2K+ 浏览量

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告