2011-11-29 45 views
0

我需要存儲爲有理數表示爲分子/分母用於存儲分數(如3/5)的新類型。我發現下面這樣做。PL/SQL中的新類型

CREATE TYPE Rational AS OBJECT ( 
    num INTEGER, 
    den INTEGER, 
    MAP MEMBER FUNCTION convert RETURN REAL, 
    MEMBER PROCEDURE normalize, 
    MEMBER FUNCTION reciprocal RETURN Rational, 
    MEMBER FUNCTION plus (x Rational) RETURN Rational, 
    MEMBER FUNCTION less (x Rational) RETURN Rational, 
    MEMBER FUNCTION times (x Rational) RETURN Rational, 
    MEMBER FUNCTION divby (x Rational) RETURN Rational, 
    PRAGMA RESTRICT_REFERENCES (DEFAULT, RNDS,WNDS,RNPS,WNPS) 
); 

如何添加分母不能爲零的約束。

回答

3

您需要爲您的類型聲明CONSTRUCTOR。那麼你可以把任何你喜歡的驗證放在身體裏。

CREATE TYPE Rational AS OBJECT ( 
    num INTEGER, 
    den INTEGER, 
    MAP MEMBER FUNCTION convert RETURN REAL, 
    MEMBER PROCEDURE normalize, 
    MEMBER FUNCTION reciprocal RETURN Rational, 
    MEMBER FUNCTION plus (x Rational) RETURN Rational, 
    MEMBER FUNCTION less (x Rational) RETURN Rational, 
    MEMBER FUNCTION times (x Rational) RETURN Rational, 
    MEMBER FUNCTION divby (x Rational) RETURN Rational, 
    constructor function rational 
      (n integer, d integer) 
      return self as result,  
    PRAGMA RESTRICT_REFERENCES (DEFAULT, RNDS,WNDS,RNPS,WNPS) 
); 

在你的身體類型添加構造函數代碼:

constructor function rational 
      (n integer, d integer) 
      return self as result 
is  
begin 
    if d = 0 then 
     raise_application_error(-20000, 'Denominator cannot be zero!'); 
    end if; 
    self.num := n; 
    self.den := d; 
end rational; 
+0

另請參見[系統定義和用戶定義的構造(http://docs.oracle.com/cd/E11882_01/appdev .112/e11822/adobjadv.htm#ADOBJ7662)來自Oracle文檔。 – user272735