2009-11-12 33 views
5

如果沒有找到行,oracle sql中是否有可能返回默認行? 我有一個過程,在取得的行中將被放在一個平坦的ascii文件。 現在我有一個要求,如果沒有行被sql查詢讀取,那麼應該有一個默認的行在ascii文件中。返回sql中的缺省行

是否有可能在sql中輸出默認行,如果查詢沒有提取行 注意:我不想使用pl/sql。

回答

6

你可以使用UNION ALL這個:

select a, b, c from foobar 
where foo='FOO' 
union all 
select 'def', 'ault', 'value' from dual 
where not exists (select 'x' from foobar where foo='FOO') 
+0

優秀answer.thanks ammoQ – Vijay 2009-11-12 13:58:03

2

我懷疑,這將是清潔劑具有與寫入的ASCII文件寫入默認的數據,如果沒有行返回,而不是讓甲骨文的過程做到這一點。如果您使用的查詢代價昂貴,則如果您將其作爲ammoQ和David Oniell完成的操作返回默認行,則會顯着增加此成本。

6

對於複雜的查詢,其中上找出是否有在結果集中的某一行的開銷是繁重或查詢僅僅是非常大而笨重,然後一個子查詢分解條款可能是有益的:

With my_query as 
    (
    select a, b, c from foobar where foo='FOO' 
    ) 
Select a,b,c 
From my_query 
Union All 
Select ... 
From dual 
Where Not Exists 
     (Select 1 from my_query) 
/
+0

不錯,我從來沒有看到 – ninesided 2009-11-12 17:09:37

+1

+1爲與第 – 2009-11-12 18:10:52

+0

如果什麼my_query使用組表達過嗎?如何在第五排使用它們? – zygimantus 2016-10-27 07:09:27

1

還有另一個(悲傷,扭曲)選項。不需要CTE或子查詢重複。

select 
    coalesce(a, 'def'), 
    coalesce(b, 'ault'), 
    coalesce(c, 'value') 
from foobar 
right join (select 1 from dual) on 1=1 
where foobar.some_condition; 
+0

什麼是'雙'? – 2017-01-02 14:08:23

+0

@AlbertoAcuña「dual」是Oracle特有的一個奇怪的約定,表示從中選擇常量的虛擬表。 – Reinderien 2017-01-02 14:10:33