我有一个使用临时表的过程。我想摆脱临时表并使用集合来删除I / O.它有大约5000条记录。
我想将数据插入此集合,然后我想访问集合,如:
select * from table(my_type_for_gtt)
我找不到这样的例子。我很困惑,我是否必须首先创建一个记录类型,然后创建表格?
有人可以举一个简短的例子吗?
答案 0 :(得分:2)
您正朝着正确的方向前进 - 首先创建您的类型
CREATE TYPE myEntry
AS
OBJECT
(attr1 NUMBER,
attr2 VARCHAR2(20)
);
CREATE TYPE myCollection AS TABLE OF myEntry;
接下来一些示例函数返回集合的“行”
CREATE OR REPLACE FUNCTION ExampleMyCollection1
RETURN myCollection
IS
lCol myCollection := myCollection(); /* Must initialise empty collection */
BEGIN
lCol.EXTEND(1000);
/* Populate the collection entries with objects */
FOR i IN 1..1000 LOOP
lCol(i) := myEntry(i,'An entry for '||i);
END LOOP;
RETURN lCol;
END ExampleMyCollection1;
SELECT * FROM TABLE(ExampleMyCollection1);
变体 - 这次我们使用流水线操作,以便在创建查询时将结果返回给查询。请注意,尽管是一个函数,但PIPELINED函数没有结束RETURN。
CREATE OR REPLACE FUNCTION ExampleMyCollection2
RETURN myCollection PIPELINED
IS
BEGIN
FOR i IN 1..1000 LOOP
PIPE ROW(myEntry(i,'An entry for '||i));
END LOOP;
END ExampleMyCollection2;
SELECT * FROM TABLE(ExampleMyCollection2);
要用纯粹的内存数据替换你的临时表,你需要一些东西来存储你的集合 - 即一个包含状态的包。
CREATE OR REPLACE PACKAGE pMyCollection
AS
PROCEDURE AddEntry(entry IN myEntry);
FUNCTION fCurrentCollection RETURN myCollection;
PROCEDURE ClearEntries;
END pMyCollection;
CREATE OR REPLACE PACKAGE BODY pMyCollection
AS
/* Stateful variable to hold the collection */
pCollection myCollection := myCollection();
PROCEDURE AddEntry(entry IN myEntry)
IS
BEGIN
pCollection.EXTEND;
pCollection(pCollection.LAST) := entry;
END;
PROCEDURE ClearEntries
IS
BEGIN
pCollection.DELETE;
END ClearEntries;
FUNCTION fCurrentCollection
RETURN myCollection
IS
BEGIN
/* Return whole collection - we could use pipelining and parameters to return partial elements */
RETURN pCollection;
END fCurrentCollection;
END pMyCollection;