2013-03-21 187 views
1

我想提出的,如果條件選擇查詢選擇?在IF條件語句

+6

什麼[RDBMS(HTTP:// EN。 wikipedia.org/wiki/Relational_database_management_system)您正在使用? 'RDBMS'代表*關係數據庫管理系統*。 'RDBMS是SQL'的基礎,並且適用於所有現代數據庫系統,如MS SQL Server,IBM DB2,Oracle,MySQL等...... – 2013-03-21 12:34:29

+1

@JW:實際上SQL是RDBMS的基礎。 – 2013-03-21 12:44:13

+0

這看起來像程序語言語法。你想要做什麼以及在哪個RDBMS中? – Rachcha 2013-03-21 12:50:03

回答

1

如果您使用SQL Server,那麼顯而易見的方法是使用EXISTS,例如,

if exists(select id from ids where id = 10) 
begin 
    print 'it exists' 
end 

另一種方法是使用等效的關鍵字SOME or ANY

if 10 = some(select id from ids) 
begin 
    print 'it exists' 
end 
+0

@ Phil-這不是Oracle SQL有效的語法。 Oracle SQL中沒有IF。請修改它。 – Art 2013-03-21 14:43:32

+0

@Art - 原始文章沒有Oracle標籤,但是OP已經接受了這一點 - 可能應該更改標籤。 – Phil 2013-03-21 15:23:34

+0

@菲爾 - 然後我因爲無所事事而沮喪了:) – Art 2013-03-21 17:05:21

-1
for (-- 
     -- The following select statement returns 
     -- records only, if there are any whose 
     -- ID = 10. 
     -- The rownum = 1 condition makes sure that 
     -- at most one record is returned. 
     -- 
     select null 
     from ids 
     where id = 10 and 
      rownum = 1) loop 

     /* 
     Do something if at least on record is selected 
     by the select statement. 
     */ 

end loop; 

這枚「解決方案」應該做你想要什麼,我並不推薦這樣做,像這樣因爲它對於後面的代碼維護者來說可能並不清楚這個for ... loop究竟是什麼目的。您可能需要考慮使用一個變量,在其中選擇id=10記錄的計數,並根據cnt>0執行您的操作。

0

這可能有所幫助 - 所有示例都等同於Oracle SQL中的IF。

CASE表達式:

SELECT deptno, empno, ename 
    , (CASE WHEN deptno = 10 THEN 1 ELSE 0 END) check_dept 
    FROM scott.emp 
ORDER BY 1 
/

DECODE()函數:

SELECT deptno, empno, ename, DECODE(deptno, 10, 1, 0) check_dept 
    FROM scott.emp 
ORDER BY 1 
/

你的榜樣 - CASE ..:

select id, (CASE WHEN id = 10 THEN 1 ELSE 0 END) AS check_id from ids where... 
/