定义子类型 我们可以在任何pl/sql块、子程序或包中定义自己的子类型,语法如下: subtype subtype_name is base_type[(constraint)] [not null ]; subtype_name就是声明的子类型的名称,base_type可以是任何标量类型或用户定义类型,约束只是用于限定基类型
定义子类型
我们可以在任何pl/sql块、子程序或包中定义自己的子类型,语法如下:
subtype subtype_name is base_type[(constraint)] [not null ];
subtype_name就是声明的子类型的名称,base_type可以是任何标量类型或用户定义类型,约束只是用于限定基类型的精度和数值范围,或是最大长度。下面举几个例子:
declare
subtype birthdate is date not null ; -- based on date type
subtype counter is natural ; -- based on natural subtype
type namelist is table of varchar2 (10);
subtype dutyroster is namelist; -- based on table type
type timerec is record (
minutes integer ,
hours integer
);
subtype finishtime is timerec; -- based on record type
subtype id_num is emp.empno%type ; -- based on column type
我们可以使用%type或%rowtype来指定基类型。当%type提供数据库字段中的数据类型时,子类型继承字段的大小约束(如果有的话)。但是,子类型并不能继承其他约束,如not null。
2、使用子类型
一旦我们定义了子类型,我们就可以声明该类型的变量、常量等。下例中,我们声明了counter类型变量,子类型的名称代表了变量的使用目的:
declare
subtype counter is natural ;
rows counter;
下面的例子演示了如何约束用户自定义子类型:
declare
subtype accumulator is number ;
total accumulator(7, 2);
子类型还可以检查数值是否越界来提高可靠性。下例中我们把子类型numeral的范围限制在-9到9之间。如果程序把这个范围之外的数值赋给numeral类型变量,那么pl/sql就会抛出一个异常。
declare
subtype numeral is number (1, 0);
x_axis numeral; -- magnitude range is -9 .. 9
y_axis numeral;
begin
x_axis := 10; -- raises value_error
...
end ;
http://blog.csdn.net/zengmuansha/archive/2010/03/30/5431728.aspx
