如果条件与表2中的字段匹配,则更新表1字段?

时间:2017-10-12 15:55:14

标签: oracle if-statement sql-update

我有两个表(参见示例数据):

示例数据:

APARTMENT TABLE               PAYMENT_STATUS TABLE                
==========================    =======================   
APARTMENT  | DEBT              APARTMENT  |STATUS   
10         |0                  10         |NULL            
22         |500                22         |NULL            
33         |250                33         |NULL

我想将“PAYMENT_STATUS”表更新为一个数字,具体取决于“APARTMENT”表中“DEBT”字段的值,假设租金价格为500,我想将“STATUS”字段更新为:

  • 如果债务为0,则将“STATUS”的值设置为3
  • 如果债务介于1和499之间,则将“STATUS”的值设置为2
  • 如果债务为500,则将“STATUS”的值设置为1

我是UPDATE语句的新手,任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:2)

使用Merge Intohttp://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606

MERGE INTO PAYMENT_STATUS m USING
(SELECT APARTMENT ,
  CASE
    WHEN DEBT = 0
    THEN 3
    WHEN DEBT BETWEEN 1 AND 499
    THEN 2
    WHEN DEBT = 500
    THEN 1
  END status
FROM APARTMENTS
) r ON ( m.APARTMENT = r.APARTMENT )
WHEN matched THEN
  UPDATE SET m.STATUS = r.STATUS;