PL / SQL减法集合

时间:2015-11-19 10:45:29

标签: sql database oracle plsql

我的pl / sql函数中有2个集合变量var1和var2。 例如,它们内部的数据是:

var1           var2
X              X
X
Y

如何用pl / sql减去这些集合,结果如下:

var1 - var2:       var2 - var1
X                  empty
Y

我的收藏类型定义如下:

create type MY_TYPE_OBJECT as (
id                  numeric(20,0),
string_val          varchar(4000),
time                timestamp)

create domain MY_TYPE_TABLE as MY_TYPE_OBJECT[];

我的变量属于MY_TYPE_TABLE类型。

1 个答案:

答案 0 :(得分:0)

假设您的集合具有相同的数据类型,那么在PL / SQL中您可以非常轻松地执行此操作

var1 multiset except var2
var2 multiset except var1

示例:

declare
    var1                sys.ora_mining_varchar2_nt := sys.ora_mining_varchar2_nt('X','X','Y');
    var2                sys.ora_mining_varchar2_nt := sys.ora_mining_varchar2_nt('X');

    var1_minus_var2     sys.ora_mining_varchar2_nt;
    var2_minus_var1     sys.ora_mining_varchar2_nt;
begin
    dbms_output.put_line('var1 has '||var1.count()||' elements');
    for i in nvl(var1.first(),1)..nvl(var1.last(),0) loop
        dbms_output.put_line('    element '||i||' = '||var1(i));
    end loop;

    dbms_output.put_line('var2 has '||var2.count()||' elements');
    for i in nvl(var2.first(),1)..nvl(var2.last(),0) loop
        dbms_output.put_line('    element '||i||' = '||var2(i));
    end loop;

    var1_minus_var2 := var1 multiset except var2;

    dbms_output.put_line('var1_minus_var2 has '||var1_minus_var2.count()||' elements');
    for i in nvl(var1_minus_var2.first(),1)..nvl(var1_minus_var2.last(),0) loop
        dbms_output.put_line('    element '||i||' = '||var1_minus_var2(i));
    end loop;

    var2_minus_var1 := var2 multiset except var1;

    dbms_output.put_line('var2_minus_var1 has '||var2_minus_var1.count()||' elements');
    for i in nvl(var2_minus_var1.first(),1)..nvl(var2_minus_var1.last(),0) loop
        dbms_output.put_line('    element '||i||' = '||var2_minus_var1(i));
    end loop;
end;
/

...产生......

的输出
var1 has 3 elements
    element 1 = X
    element 2 = X
    element 3 = Y
var2 has 1 elements
    element 1 = X
var1_minus_var2 has 2 elements
    element 1 = X
    element 2 = Y
var2_minus_var1 has 0 elements

享受!