如何在Oracle db中编写具有三个条件的if语句

How to write if statement which has three conditions in Oracle db

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

我有四个table。

Table1 : t1

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

Table 2: t2

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

Table 3: t3

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

结果 table : t4

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

tablet1,t2相同。当输入的是“2003”时,检查t1、t2是否有“2003”,将t3中“2003”的CustomerID复制到t4。

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

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 |

因此,您正在对 t3 中的行进行 insert/select 处理(假设您不想与现有数据合并),其中提供的年份存在于其他两个表中?即:

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)