2014-01-20 24 views
0

我有這樣的查詢。在Oracle中用VIEW替換WITH WITH子句

with test1 as (  
select emp.empno, emp.deptno, emp.name, emp.hiredate, dept.deptname 
from emp, dept 
where 
emp.deptno = dept.deptno 
and emp.deptno = 72 
and emp.salary > 5000 
) 
select inner1.* 
from ( 
select 'abc' as title, 
1 emp_order, 
name, hiredate, deptname 
from test1 
UNION ALL 
select 'xyz' as title, 
2 emp_order, 
name, hiredate, deptname 
from test1 
) inner1 

我想完全刪除WITH子句並創建一個VIEW。我唯一的問題是WITH子句中的動態值。

我嘗試這樣做:

CREATE VIEW testview as 
select emp.empno, emp.deptno, emp.name, emp.hiredate, dept.deptname 
from emp, dept 
where 
emp.deptno = dept.deptno 
and emp.deptno = 72 
and emp.salary > 5000 

更新查詢

select inner1.* 
    from ( 
    select 'abc' as title,  
    1 emp_order,  
    name, hiredate, deptname  
    from testview  
    UNION ALL  
    select 'xyz' as title,  
    2 emp_order, 
    name, hiredate, deptname  
    from testview 
    ) inner1 

在這種情況下,我怎麼能傳遞綁定值,薪金和視圖DEPTNO的cols?

+0

動態值,你指的是什麼,它是不是創造你在問什麼? – 2014-02-03 20:06:22

回答

0

爲了在視圖中使用此查詢,您不需要刪除公用表表達式。如果刪除謂詞並將其應用於查詢,則可以將它們推入CTE內部。

例如

CREATE VIEW testview as 
select emp.empno, emp.deptno, emp.name, emp.hiredate, dept.deptname, emp.salary 
from emp join dept ON emp.deptno = dept.deptno; 

select inner1.* 
from ( 
    select 'abc' as title,  
     1 emp_order,  
     name, hiredate, deptname  
    from testview 
    where deptno = 72 and salary > 5000  
    UNION ALL  
    select 'xyz' as title,  
     2 emp_order, 
     name, hiredate, deptname  
    from testview 
    where deptno = 72 and salary > 5000  
) inner1 
+0

在你的解決方案中,如果視圖的基礎表很大,並且在沒有發生謂詞推送的情況下,視圖的性能不會很差? – vishad

+0

那裏有兩個「ifs」,並且不推動謂詞不太可能。另一方面,如果CTE結果集足夠大以便實現,則子查詢只執行一次,性能優於重複邏輯的內聯視圖。 CTE也有好處 - 如果他們不這樣做,他們就不會存在。 –

1

如果我理解正確,那麼你想在你的視圖中使用參數。

要做到這一點,你可以使用下面的方法之一:

a)如果您的參數都或多或少是靜態的,而不是頻繁變化,您可以使用一個表來存儲這些參數的值。此表中的值可以使用PL/SQL包或過程進行更新。這張表格可以在您的視圖中被引用。

灣)如果您需要針對不同的時段設置不同的參數值,你也可以嘗試使用應用程序上下文給出here

希望它可以幫助

Vishad