我有一個視圖比較兩個表(tableYesterday和tableToday)中的數據並輸出基於比較的結果。讓我們調用這個視圖:ViewComp。創建填充,然後從視圖中刪除表(Oracle)
我需要做的比這更多。通過單一視圖,我實際上需要:
- 創建或替換
tableToday
並預先填充它。 - 執行
ViewComp
查詢。 - 替換
tableYesterday
與tableToday
。
我研究過像嵌套視圖這樣的東西,但是我找不到從視圖中執行1和3的方法。我會很感激任何想法。謝謝。
我有一個視圖比較兩個表(tableYesterday和tableToday)中的數據並輸出基於比較的結果。讓我們調用這個視圖:ViewComp。創建填充,然後從視圖中刪除表(Oracle)
我需要做的比這更多。通過單一視圖,我實際上需要:
tableToday
並預先填充它。ViewComp
查詢。tableYesterday
與tableToday
。我研究過像嵌套視圖這樣的東西,但是我找不到從視圖中執行1和3的方法。我會很感激任何想法。謝謝。
你不能做這種事。您可以創建PL/SQL過程來執行步驟或創建實體化視圖。
這幾乎肯定是一個壞主意。意見不應該「做」任何事情。
對於那些極少數情況下,這是必需的,它可以用下面的技巧來完成。你一定要記錄這段代碼,向其他人解釋你在做什麼以及爲什麼。
採樣模式和對象
--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
- -
感謝喬恩!我已經創建了上面的組件並執行了該視圖。它正如你所描述的那樣工作。在這個時候,我要花上一兩分鐘的時間來確保我完全理解你所做的。我很快可能會有後續問題。再次感謝您的所有幫助! –
嗯,我得到一個運行時錯誤執行上面的代碼與我需要我的情況下的修改。我已經包含了我的代碼,希望你能幫助我(看看我對代碼編輯的這個問題)。任何幫助非常感謝! –
順便說一下,我得到的錯誤是 「ORA-00911:無效字符」,它在以下區域: 執行立即q'[ select cast(collect(PRESIDENTCOMP_TYPE(flag,ID,FIRSTNAME,LASTNAME ))作爲PRESIDENTCOMP_NT) –