【问题标题】:How to write if statement which has three conditions in Oracle db如何在Oracle db中编写具有三个条件的if语句
【发布时间】:2015-12-10 00:11:07
【问题描述】:

我使用 Oracle 数据库。我很困惑如何在存储过程中编写 if 条件。

我有四张桌子。

表 1:t1

╔════════════╦═════╗
║ CustomerID ║ Year║
╠════════════╬═════╣
║ ACC20011   ║ 2001║
║ ACC30122   ║ 2001║
║ ACC12356   ║ 2002║
║ EVG12345   ║ 2003║
║ DAA23445   ║ 2003║
║ DAA23548   ║ 2003║
╚════════════╩═════╝

表 2:t2

╔════════════╦═════╗
║ CustomerID ║ Year║
╠════════════╬═════╣
║ ACC20011   ║ 2001║
║ ACC30122   ║ 2001║
║ ACC12356   ║ 2002║
║ EVG12345   ║ 2003║
║ DAA23445   ║ 2003║
║ DAA23548   ║ 2003║
╚════════════╩═════╝

表 3:t3

╔════════════╦═════╗
║ CustomerID ║ Year║
╠════════════╬═════╣
║ ACC20011   ║ 2001║
║ ACC30122   ║ 2002║
║ ACC00001   ║ 2003║
║ EVG00002   ║ 2003║
║ DAA23048   ║ 2003║
║ DAA23548   ║ 2001║
╚════════════╩═════╝

结果表:t4

╔════════════╦═════╗
║ CustomerID ║ Year║
╠════════════╬═════╣
║ ACC00001   ║ 2003║
║ EVG00002   ║ 2003║
║ DAA23048   ║ 2003║
╚════════════╩═════╝

表 t1、t2 相同。当输入为“2003”时,应检查t1、t2是否存在“2003”,并将t3中“2003”的CustomerID复制到t4。

我很困惑如何给出 if 条件。年份应该在所有三个表中。如果在 t1、t2、t3 中为“2003”,则更新 t4。

【问题讨论】:

  • 当然,如果您遇到一个小问题,您现在必须编写一个不完整的程序。可以发一下吗?

标签: oracle stored-procedures plsql oracle-sqldeveloper


【解决方案1】:

SQL Fiddle

查询

insert into t4
select * from t3
where year_nr = 2003
and exists (
    select 1 from t1
    where year_nr = 2003
    )
and exists (
    select 1 from t2
    where year_nr = 2003
    )

查询

select * from t4

Results

| CUSTOMER_ID | YEAR_NR |
|-------------|---------|
|    ACC00001 |    2003 |
|    EVG00002 |    2003 |
|    DAA23048 |    2003 |

【讨论】:

  • 是否有任何解决方案,而不是使用 where exists 在运行时进行检查。如果条件满足怎么写 if 语句 insert else 什么都不做。
【解决方案2】:

因此,您正在对 t3 中的其他两个表中存在所提供年份的行进行插入/选择(假设您不想与现有数据合并)?那就是:

insert into t4 (CustomerId, Year)
select CustomerId, Year
from t3 
where Year = :year
and exists (select 1 from t2 where Year = :year)
and exists (select 1 from t1 where Year = :year)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多