我正在尝试使用Oracles对象关系功能创建一些分层数据。
我已经定义了一个“帖子”如下:
create type Post as object (title varchar(20), body varchar(2000),
author varchar(200), parent REF Post,
MEMBER FUNCTION numReplies RETURN NUMBER,
PRAGMA RESTRICT_REFERENCES(numReplies, WNDS)
);
/
create table Posts of Post;
现在我想编写函数numReplies来找出有多少帖子有“自我”帖子作为父母:
create or replace type body Post AS
MEMBER FUNCTION numReplies RETURN number IS
i INT;
BEGIN
SELECT COUNT(*) INTO i FROM Posts p WHERE p.parent = SELF;
RETURN i;
END;
END;
/
但是我收到了编译错误:
Warning: Type Body created with compilation errors.
SQL> show errors;
Errors for TYPE BODY POST:
LINE/COL ERROR
-------- -----------------------------------------------------------------
6/3 PL/SQL: SQL Statement ignored
6/56 PL/SQL: ORA-00932: inconsistent datatypes: expected TSTER123.POST
got REF TSTER123.POST
我已经尝试在where子句中执行REF(SELF),我得到相同的错误消息。我也试过REF(p.parent)(反正没有意义)我得到错误:
LINE/COL ERROR
-------- -----------------------------------------------------------------
6/3 PL/SQL: SQL Statement ignored
6/49 PL/SQL: ORA-00904: "P"."PARENT": invalid identifier
我想使用OR功能(它是一个类项目)所以我不想诉诸于添加ID列来发布和使用它。我怎样才能做到这一点?
注意:以下查询有效,我无法让它在使用SELF的函数中工作。
SELECT title, (select count(*) from Posts p2 where p2.parent = REF(p))
FROM Posts p;
修改
好的,我已经把它编译好了,但是我没有得到我期望的数据。
以下是我使用的一些虚拟数据:
insert into Posts values ('foo', 'bar', 'tyler', null);
insert into Posts values ('hello world', 'bar', 'jatin', (select REF(p) FROM Posts p where p.title = 'foo'));
insert into Posts values ('bark', 'asd', 'tom', (select REF(p) FROM Posts p where p.title = 'hello world'));
insert into Posts values ('friendly', 'hgfags', 'tyler', (select REF(p) FROM Posts p where p.title = 'foo'));
以下是编译内容:
create or replace type body Post AS
MEMBER FUNCTION numReplies RETURN number IS
i INT;
BEGIN
SELECT COUNT(*) INTO i FROM Posts p WHERE DEREF(p.parent) = SELF;
RETURN i;
END;
END;
/
但是,我没有得到正确的结果:
SQL> SELECT title, (select count(*) from Posts p2 where p2.parent = REF(p)) From Posts p;
TITLE (SELECTCOUNT(*)FROMPOSTSP2WHEREP2.PARENT=REF(P))
-------------------- ------------------------------------------------
foo 2
hello world 1
bark 0
friendly 0
SQL> select title, p.numReplies() from Posts p;
TITLE P.NUMREPLIES()
-------------------- --------------
foo 0
hello world 1
bark 0
friendly 0
如果我使用它:
create or replace type body Post AS
MEMBER FUNCTION numReplies RETURN number IS
i INT;
BEGIN
SELECT COUNT(*) INTO i FROM Posts p WHERE DEREF(p.parent).title = SELF.title;
RETURN i;
END;
END;
/
我得到了预期的结果,但我要求每个帖子都有一个独特的标题。