2015-06-05 65 views
0

我有一個包含值「1」如何在如果條件中使用select語句

可變

當前代碼:

if var1 in (1, 2, 3, 4) then ... 

要求的格式(我不想硬編碼的比較值):

if var1 in (select col1 from table1) then ... 

Select col1 from table1; 

1 
2 
3 
4 
+0

您使用的數據庫是? –

+0

Oracle數據庫.. – Krishhh

回答

1

取決於你使用,你可以select語句結果返回到一個數組或對象之後,你可以在數組或對象上執行條件語句的語言:

EX。 如果VAR1 ARR ..

0

我認爲這應該是周圍的方式。

select count(*) from table1 into var1_cnt 
where table1.col1 = var1; 

if var1_cnt > 0 then 
....... 
end if; 
1

這裏是做正確的方法:

declare 
    rid rowid; 
begin 
    --prior logic 
    begin 
     select rowid into rid from table1 where table1.col1=var1; 
     -- condition is met here, do the then part 
    exception 
     when no_data_found then 
      --this is the else part, if you do not want to do anything, then 
      -- just put null; 
    end; 
    --subsequent logic 
end; 

爲什麼這是正確的方法:

  • 它不使用count(*),你是不是想要獲得匹配記錄的計數,您只需測試存在。
  • 這是最快的方法,如果col1被索引,你將不會讀取任何表數據,只是索引。
  • 您避免了雙重比較,一次在select子句中,一次在if語句中。