Plsql 如何在PL/SQL中创建枚举类型?

Plsql 如何在PL/SQL中创建枚举类型?,plsql,Plsql,例如,我想创建自己的布尔类型并将其命名为Bool。我该怎么做 或者一种交通灯类型,即只有红色、黄色、绿色(当然为空)。 除了常量之外,blog还定义了有效颜色的子类型 SQL> declare 2 RED constant number(1):=1; 3 GREEN constant number(1):=2; 4 BLUE constant number(1):=3; 5 YELLOW constant number(1):=4; 6 -- 7 VIO

例如,我想创建自己的布尔类型并将其命名为Bool。我该怎么做

或者一种交通灯类型,即只有红色、黄色、绿色(当然为空)。

除了常量之外,blog还定义了有效颜色的子类型

SQL> declare
  2  RED constant number(1):=1;
  3  GREEN constant number(1):=2;
  4  BLUE constant number(1):=3;
  5  YELLOW constant number(1):=4;
  6  --
  7  VIOLET constant number(1):=7;
  8  --
  9  subtype colors is binary_integer range 1..4;
 10  --
 11  pv_var colors;
 12  --
 13  function test_a (pv_var1 in colors) return colors
 14  is
 15  begin
 16     if(pv_var1 = YELLOW) then
 17             return(BLUE);
 18     else
 19             return(RED);
 20     end if;
 21  end;
 22  --

我能想到的最接近的是:

create or replace type lights as object
(
  red varchar2(8),
  yellow varchar2(8),
  green varchar2(8),
constructor function lights return self as result
)
和机构:

create or replace type body lights is
constructor function lights return self as result is
begin
  self.red = 'red';
  self.yellow = 'yellow';
  self.green = 'green';
  return;
end;
end;
然后在代码中可以使用它:

declare
l lights := new lights;
begin
   dbms_output.put_line(l.red);
end;

我认为A.B.Cade提供的解决方案并不完全正确。让我们假设这样的过程:

procedure TestEnum(灯中的枚举)

中的
enum_的值是多少?红色黄色的?绿色

我提出另一个解决办法。下面是一个包示例

CREATE OR REPLACE PACKAGE pkg_test_enum IS

  SUBTYPE TLight IS BINARY_INTEGER RANGE 0..2;
  Red CONSTANT TLight := 0;
  Yellow CONSTANT TLight := 1;
  Green CONSTANT TLight := 2;

  --get sting name for my "enum" type
  FUNCTION GetLightValueName(enum_in TLight) RETURN VARCHAR2;

  PROCEDURE EnumTest(enum_in TLight);

END pkg_test_enum;


CREATE OR REPLACE PACKAGE BODY pkg_test_enum IS 
  FUNCTION GetLightValueName(enum_in TLight) 
  RETURN VARCHAR2
  IS
    ResultValue VARCHAR2(6);
  BEGIN
    CASE enum_in 
      WHEN Red THEN ResultValue := 'Red';
      WHEN Green THEN ResultValue := 'Green';
      WHEN Yellow THEN ResultValue := 'Yellow';
      ELSE ResultValue := '';
    END CASE;
    RETURN ResultValue;
  END GetLightValueName;


  PROCEDURE EnumTest(enum_in TLight)
  IS
  BEGIN
    --do stuff
    NULL;
  END EnumTest;
END pkg_test_enum;
begin
  pkg_test_enum.EnumTest(pkg_test_enum.Red);
end;
我现在可以在不同的软件包中使用
TLight
。我现在可以在
中根据预定义值或null测试
enum_

下面是一个使用示例

CREATE OR REPLACE PACKAGE pkg_test_enum IS

  SUBTYPE TLight IS BINARY_INTEGER RANGE 0..2;
  Red CONSTANT TLight := 0;
  Yellow CONSTANT TLight := 1;
  Green CONSTANT TLight := 2;

  --get sting name for my "enum" type
  FUNCTION GetLightValueName(enum_in TLight) RETURN VARCHAR2;

  PROCEDURE EnumTest(enum_in TLight);

END pkg_test_enum;


CREATE OR REPLACE PACKAGE BODY pkg_test_enum IS 
  FUNCTION GetLightValueName(enum_in TLight) 
  RETURN VARCHAR2
  IS
    ResultValue VARCHAR2(6);
  BEGIN
    CASE enum_in 
      WHEN Red THEN ResultValue := 'Red';
      WHEN Green THEN ResultValue := 'Green';
      WHEN Yellow THEN ResultValue := 'Yellow';
      ELSE ResultValue := '';
    END CASE;
    RETURN ResultValue;
  END GetLightValueName;


  PROCEDURE EnumTest(enum_in TLight)
  IS
  BEGIN
    --do stuff
    NULL;
  END EnumTest;
END pkg_test_enum;
begin
  pkg_test_enum.EnumTest(pkg_test_enum.Red);
end;
此外,您可以使此类型不可为null


子类型TLight是二进制整数,范围0..2不为空

我以前使用过与@mydogtom和@klas lindbäck相同的方法。我在试图刷新记忆时发现了这个。然而,@a-b-cade建议的对象方法让我思考。我同意@mydogtom所描述的问题(价值是什么?),但它让我想到使用对象是可能的

我想到的是一种方法,它使用一个具有单成员属性的对象作为枚举的值,使用静态函数作为每个可能的值。我看不出如何与子类型组合以获得对值字段的真正限制,而不是正式地使其不为null。但是,我们可以在构造函数中验证它。与“适当的”枚举(例如在Java中)相比,功能上的缺点是我们无法阻止某人直接将
val
属性更新为无效值。然而,只要人们使用构造函数和set_value函数,它是安全的。我不确定这些开销(无论是在创建对象的运行时还是在维护对象等方面)是否值得,所以我可能会继续使用@mydogtom描述的方法,但我不确定

您也可以将name作为属性,并在
set_value
中进行设置(有点像@a-b-cade的版本),但这会添加另一个可以直接更新的属性,从而增加另一组val和name不匹配的状态,因此我更喜欢将name作为函数的方法

这种用法的一个示例是(使用下面的my
demo\u enum
类型):

我所做的是定义一个基类,尽可能多地使用它:实际的
val
字段、
equals
静态值函数、
set\u value
to\u string
函数。还有
name
函数,但这只是被重写(看不到如何正式地使成员函数抽象,所以基础版本只是抛出一个异常)。我使用
name
也是为了检查值是否有效,以减少枚举可能值所需的位置数

create or replace type enum_base as object(
    -- member field to store actual value
    val integer,

    -- Essentially abstract name function
    -- Should be overridden to return name based on value
    -- Should throw exception for null or invalid values
    member function name return varchar2,

    --
    -- Used to update the value.  Called by constructor
    --
    member procedure set_value(pvalue in integer),
    
    --
    -- Checks the current value is valid
    -- Since we can't stop someone updating the val property directly, you can supply invalid values
    --
    member function isValid return boolean,
    
    --
    -- Checks for equality with integer value 
    -- E.g. with a static function for a possible value:   enum_var.equals( my_enum_type.someval() )
    --    
    member function equals(other in integer) return boolean,
        
    --
    -- For debugging, prints out name and value (to get just name, use name function)
    --      
    member function to_string return varchar2
    
    
) not instantiable not final;
/

create or replace type body enum_base is

    member function name return varchar2 is
    begin
        -- This function must be overriden in child enum classes.
        -- Can't figure out how to do an abstract function, so just throw an error
        raise invalid_number;
    end;
    
    member procedure set_value(pvalue in integer) is
        vName varchar2(3);
    begin
        self.val := pvalue;
        -- call name() in order to also validate that value is valid
        vName := self.name;                          
    end set_value;
    
            
    member function isValid return boolean is
        vName varchar2(3);
    begin
        begin
            -- call name() in order to also validate that value is valid
            vName := self.name;   
            return true; 
        exception
            when others then
                return false;
        end;            
    end isValid;
    
    
    member function equals(other in integer) return boolean is
    begin
        return self.val = other;
    end equals;
    
    member function to_string return varchar2 is
    begin 
        if self.val is null then
            return 'NULL';
        end if;

        return self.name || ' (' || self.val || ')';
    end to_string;
end;
/
在实际的enum类中,我必须定义一个构造函数(它只调用
set\u value
)并重写
name
函数以返回每个可能值的名称。然后,我为每个可能的值定义一个静态函数,该函数返回该值的整数索引。最后,我定义了一个重载
equals
,与同一类型的另一个枚举进行比较。如果要将其他属性附加到每个值,则可以通过定义其他函数来实现

create or replace type demo_enum under enum_base (
            
    -- Note: the name of the parameter in the constructor MUST be the same as the name of the variable.  
    -- Otherwise a "PLS-00307: too many declarations" error will be thrown when trying to instanciate
    -- the object using this constructor         
    constructor function demo_enum(val in integer) return self as result,
    
    --
    -- Override name function from base to give name for each possible value and throw 
    -- exception for null/invalid values
    --
    overriding member function name return varchar2,
    
    --
    -- Check for equality with another enum object
    --  
    member function equals(other in demo_enum) return boolean,

    
    --
    -- Define a function for each possible value
    --
    static function foo return integer,
    static function bar return integer
        
) instantiable final;
/

create or replace type body demo_enum is
    
    constructor function demo_enum(val in integer) return self as result is        
    begin   
        self.set_value(val);        
        return;     
    end demo_enum;
    
    
    overriding member function name return varchar2 is
    begin
        if self.val is null then
            raise invalid_number;
        end if;
        
        case self.val
            when demo_enum.foo() then
                return 'FOO';
            when demo_enum.bar() then
                return 'BAR';
            else 
                raise case_not_found; 
        end case;
    end;    
        
    member function equals(other in demo_enum) return boolean is
    begin
        return self.val = other.val;
    end equals;
            
    static function foo return integer is
    begin 
        return 0;
    end foo;
    
    static function bar return integer is
    begin 
        return 1;
    end bar;    

end;
/
这是可以测试的。我定义了两组测试。一个是针对该特定枚举的手动测试集,也是为了说明用法:

--
-- Manual tests of the various functions in the enum
--
declare
    foo demo_enum := demo_enum(demo_enum.foo());
    alsoFoo demo_enum := demo_enum(demo_enum.foo());
    bar demo_enum := demo_enum(demo_enum.bar());
    
    vName varchar2(100);    
    
    procedure assertEquals(a in varchar2, b in varchar2) is
    begin
        if a <> b then
            raise invalid_number;
        end if;
    end assertEquals;
    
    procedure assertEquals(a in boolean, b in boolean) is
    begin
        if a <> b then
            raise invalid_number;
        end if;
    end assertEquals;
    
    procedure test(vName in varchar2, enum in demo_enum, expectFoo in boolean) is
    begin
        dbms_output.put_line('Begin Test of ' || vName);
        if enum.equals(demo_enum.foo()) then
            dbms_output.put_line(vName || ' is foo');
            assertEquals(expectFoo, true);
        else
            dbms_output.put_line(vName || ' is not foo');
            assertEquals(expectFoo, false);
        end if;
        
        if enum.equals(demo_enum.bar()) then
            dbms_output.put_line(vName || ' is bar');
            assertEquals(expectFoo, false);
        else
            dbms_output.put_line(vName || ' is not bar');
            assertEquals(expectFoo, true);
        end if;
                
        if enum.equals(foo) then
            dbms_output.put_line(vName || '.equals(vFoo)');
            assertEquals(expectFoo, true);
        else
            assertEquals(expectFoo, false);
        end if;
        
        if expectFoo then
            assertEquals(enum.name, 'FOO');
        else
            assertEquals(enum.name, 'BAR');
        end if;
        
        assertEquals(enum.isValid, true);
        
        case enum.val
            when demo_enum.foo() then
                dbms_output.put_line(vName || ' matches case foo');
            when demo_enum.bar() then
                dbms_output.put_line(vName || ' matches case bar');
            else
                dbms_output.put_line(vName || ' matches no case!!!');
        end case;
        
        dbms_output.put_line(vName || ': ' || enum.to_string());
        dbms_output.put_line('--------------------------------------------------');
        dbms_output.put_line('');
    end test;
begin    
    test('foo', foo, true);
    test('bar', bar, false);
    test('alsoFoo', alsoFoo, true);
        
    
    foo.val := -1;
    assertEquals(foo.isValid, false);    
    begin
        vName := foo.name;    
    exception
        when case_not_found then
            dbms_output.put_line('Correct exception for fetching name when invalid value: ' || sqlerrm);
    end;
    
    foo.val := null;
    assertEquals(foo.isValid, false);    
    begin
        vName := foo.name;    
    exception
        when invalid_number then
            dbms_output.put_line('Correct exception for fetching name when null value: ' || sqlerrm);
    end;
end;

事实并非如此——我发现了一个博客,并没有认真阅读。按照我修改后的答案中的链接,你会发现如何做到这一点。SQLPlus friendly也适用于这两个示例。谢谢Zulu。我在答案中直接添加了关键部分。
--
-- generated test that no two values are equal 
--
declare
    vSql varchar2(4000) := '';
    
    typename constant varchar2(20) := 'demo_enum';
    
    cursor posvals is   
        select procedure_name
        from user_procedures
        where object_name = upper(typename)
          and procedure_name not in (upper(typename), 'EQUALS', 'NAME');

    cursor posvals2 is   
        select procedure_name
        from user_procedures
        where object_name = upper(typename)
          and procedure_name not in (upper(typename), 'EQUALS', 'NAME');


    procedure addline(line in varchar2) is
    begin
        vSql := vSql || line || chr(10);
    end;
begin
    addline('declare');
    addline('   enum ' || typename || ';');
    addline('begin');
        
    for posval in posvals loop    
        addline('   enum := ' || typename || '(' || typename || '.' || posval.procedure_name || '());');    
        for otherval in posvals2 loop
            addline('   if enum.equals(' || typename || '.' || otherval.procedure_name || '()) then');
            if otherval.procedure_name = posval.procedure_name then                 
                addline('      dbms_output.put_line(''' || otherval.procedure_name || ' = ' || posval.procedure_name || ''');');
            else
                addline('      raise_application_error(-20000, ''' || otherval.procedure_name || ' = ' || posval.procedure_name || ''');');
            end if;
            addline('   else');
            if otherval.procedure_name = posval.procedure_name then                 
                addline('      raise_application_error(-20000, ''' || otherval.procedure_name || ' != ' || posval.procedure_name || ''');');
            else
                addline('      dbms_output.put_line(''' || otherval.procedure_name || ' != ' || posval.procedure_name || ''');');
            end if;
            addline('   end if;');
        end loop;        
        addline('');
    end loop;
    addline('end;');
    
    execute immediate vSql;
end;