2013-03-21 122 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... 
/