Where 子句中的 if 语句

If statement within Where clause(Where 子句中的 if 语句)
本文介绍了Where 子句中的 if 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个在WHERE"子句中包含IF"语句的查询.但是 PLSQL Developer 在执行时出现了一些错误.任何人都可以帮助我进行正确的查询吗?这是查询:

I am working with a query which contains "IF" statements within a "WHERE" clause. But PLSQL Developer is giving some errors while executing it. Can anyone please help me with the correct query? Here is the query:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE IF status_flag = STATUS_ACTIVE then t.status = 'A'
       IF status_flag = STATUS_INACTIVE then t.status = 'T'
       IF source_flag = SOURCE_FUNCTION then t.business_unit = 'production'
       IF source_flag = SOURCE_USER then t.business_unit = 'users'
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

我收到错误ORA-00920:关系运算符无效".

I receive the error "ORA-00920: invalid relational operator".

status_flag = STATUS_ACTIVE 周围放置括号会导致错误ORA-00907:缺少右括号"

Placing brackets around status_flag = STATUS_ACTIVE results in error "ORA-00907: missing right parenthesis"

推荐答案

CASE 或许能帮到你:

CASE might help you out:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
                        WHEN status_flag = STATUS_INACTIVE THEN 'T'
                        ELSE null END)
   AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
                               WHEN source_flag = SOURCE_USER THEN 'users'
                               ELSE null END)
   AND t.first_name LIKE firstname
   AND t.last_name LIKE lastname
   AND t.employid LIKE employeeid;

CASE 语句 评估多个条件以生成单个值.因此,在第一次使用时,我检查 status_flag 的值,根据它的值返回 'A'、'T' 或 null,并将其与 t.status 进行比较.我使用第二个 CASE 语句对 business_unit 列执行相同操作.

The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.

这篇关于Where 子句中的 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

SQL to Generate Periodic Snapshots from Transactions Table(用于从事务表生成定期快照的SQL)
MyBatis support for multiple databases(MyBatis支持多个数据库)
Oracle 12c SQL: Missing column Headers in result(Oracle 12c SQL:结果中缺少列标题)
SQL query to find the number of customers who shopped for 3 consecutive days in month of January 2020(查询2020年1月连续购物3天的客户数量)
How to get top 10 data weekly (This week, Previous week, Last month, 2 months ago, 3 month ago)(如何每周获取前十大数据(本周、前一周、上个月、2个月前、3个月前))
Select the latest record for an Id per day - Oracle pl sql(选择每天ID的最新记录-Oracle pl SQL)