创建填充,然后从视图中删除表(Oracle)

时间:2016-11-09 20:02:32

标签: sql oracle

我有一个视图,比较两个表(tableY yesterday和tableToday)中的数据,并根据比较输出结果。让我们称之为:ViewComp。

我需要做的不仅仅是这个。用一个视图,我实际上需要:

  1. 创建或替换tableToday并预先填充它。
  2. 执行ViewComp查询。
  3. tableYesterday替换为tableToday
  4. 我研究了嵌套视图之类的东西,但是我找不到从视图中执行1和3的方法。我会很感激任何想法。谢谢。

2 个答案:

答案 0 :(得分:1)

这几乎肯定是一个坏主意。观点不应该“做”任何事情。

对于极少数需要这种情况的情况,可以使用下面的技巧来完成。您肯定希望记录此代码,向其他人解释您正在做什么以及为什么。

示例架构和对象

--Create table.
create table tableYesterday(a number, b number);

--Create abstract data type to hold one row of data to be returned by the view.
create or replace type ViewComp_type is object
(
    a number,
    b number
);

--Create nested table to hold multiple rows of data to be returned by the view.
create or replace type ViewComp_nt is table of ViewComp_type;

返回结果的功能

--Create function to return data.
create or replace function ViewComp_function return ViewComp_nt authid current_user as
    --This pragma is necessary for a function that will perform DML.
    pragma autonomous_transaction;

    v_results ViewComp_nt;

    v_name_already_exists exception;
    pragma exception_init(v_name_already_exists, -955);
begin
    --Try to create today's table.  Ignore errors if it exists.
    begin
        execute immediate 'create table tableToday(a number, b number)';
    exception when v_name_already_exists then
        execute immediate 'truncate table tableToday';
    end;

    --Populate today's table.
    execute immediate 'insert into tableToday values(1,1)';

    --Get the difference.
    execute immediate q'[
        select cast(collect(ViewComp_type(a,b)) as ViewComp_nt)
        from
        (
            select * from tableToday
            minus
            select * from tableYesterday
        )
    ]' into v_results;

    --Remove yesterday's data.
    execute immediate 'truncate table tableYesterday';

    --Replace it with today's data.
    execute immediate 'insert into tableYesterday select * from tableToday';
    commit;

    --Return the difference.
    return v_results;
end;
/

创建视图以返回函数的数据

create or replace view ViewComp as
select * from table(ViewComp_function);

测试运行

--First execution:
select * from ViewComp;

A   B
-   -
1   1

--Second execution:
select * from ViewComp;

A   B
-   -

答案 1 :(得分:0)

你不能在视野中做这些事情。您可以创建PL / SQL过程来执行步骤或创建物化视图。