从2个REF< d列中获取两个日期之间的差异

时间:2017-10-06 07:59:37

标签: sql database oracle plsql

我是SQL的新手,我试图在两个REF< d列值之间获取两个值之间的日期。 我目前的表格设置如下:

CREATE OR REPLACE TYPE Person_Type AS OBJECT
(PersonId NUMBER,
DateBorn DATE)

CREATE OR REPLACE TYPE Movie_Type AS OBJECT
(MovieId NUMBER,
ReleaseDate DATE)

CREATE OR REPLACE TYPE Role_Type AS OBJECT
(PersonId REF Person_Type,
MovieId REF Movie_Type,
Name VARCHAR2(40),
MAP MEMBER FUNCTION Actor_Age RETURN NUMBER)

数据插入如下:

INSERT INTO Person_Table
VALUES (10000, '11-NOV-1974')

INSERT INTO Movie_Table
VALUES(1000000, '19-DEC-1997')

INSERT INTO Role_Table
VALUES((SELECT REF(a) FROM Person_Table a WHERE a.PersonId = 10000),
(SELECT REF(b) FROM Movie_Table b WHERE b.MovieId = 1000000),
'Some Person')

我试图让方法Actor_Age返回某人出生那天与电影上映日期之间的差异。我已经尝试过以下但是它不会编译..

CREATE OR REPLACE TYPE BODY Role_Type
AS
   MAP MEMBER FUNCTION Actor_Age
      RETURN NUMBER
   IS
   BEGIN
    RETURN (MONTHS_BETWEEN((SELECT g.PersonId.DateBorn FROM Role_Table g),
(SELECT f.MovieId.Releasedate FROM Role_Table f)/12));
     END;
 END;

2 个答案:

答案 0 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

CREATE OR REPLACE TYPE Person_Type AS OBJECT
(PersonId NUMBER,
DateBorn DATE)
/

CREATE OR REPLACE TYPE Movie_Type AS OBJECT
(MovieId NUMBER,
ReleaseDate DATE)
/

CREATE OR REPLACE TYPE Role_Type AS OBJECT
(PersonId REF Person_Type,
MovieId REF Movie_Type,
Name VARCHAR2(40),
MAP MEMBER FUNCTION Actor_Age RETURN NUMBER)
/

CREATE OR REPLACE TYPE BODY Role_Type
AS
  MAP MEMBER FUNCTION Actor_Age
    RETURN NUMBER
  IS
    p_age NUMBER;
  BEGIN
    SELECT MONTHS_BETWEEN(
             DEREF( MovieID ).ReleaseDate,
             DEREF( PersonID ).DateBorn
           ) / 12
    INTO   p_age
    FROM   DUAL;
    RETURN p_age;
  END;
END;
/

CREATE TABLE Person_Table OF Person_Type
/
CREATE TABLE Movie_Table OF Movie_Type
/
CREATE TABLE Role_Table OF Role_Type
/

INSERT INTO Person_Table VALUES ( 10000, DATE '1970-01-01' )
/
INSERT INTO Movie_Table VALUES ( 1000000, DATE '2000-01-01' )
/
INSERT INTO Role_Table VALUES(
  (SELECT REF(a) FROM Person_Table a WHERE a.PersonId = 10000),
  (SELECT REF(b) FROM Movie_Table b WHERE b.MovieId = 1000000),
  'Some Person'
)
/

查询1

SELECT Name,
       r.Actor_Age()
FROM   Role_table r

<强> Results

|        NAME | R.ACTOR_AGE() |
|-------------|---------------|
| Some Person |            30 |

答案 1 :(得分:0)

在pl sql中,你必须使用构造select into

CREATE OR REPLACE TYPE BODY Role_Type
AS
   MAP MEMBER FUNCTION Actor_Age
      RETURN NUMBER
   IS
    v_date_born date ;
    v_realse_date date ;
   BEGIN
     SELECT deref(self.PersonId).DateBorn into v_date_born  FROM dual;
    SELECT deref(self.MovieId).Releasedate into v_realse_date FROM dual;
    RETURN (MONTHS_BETWEEN(v_date_born,v_realse_date)/12);
     END;
 END;