1

我正在尝试使用 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 来找出有多少帖子将“self”帖子作为父帖子:

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;
/

我得到了预期的结果,但我要求每个帖子都有一个唯一的标题。

4

0 回答 0