【问题标题】:Need to update column based on incoming value in oracle需要根据 oracle 中的传入值更新列
【发布时间】:2020-04-27 18:39:19
【问题描述】:

如何实现以下场景?我有下面的表结构:

 ----------------------------
| ID | COL_1 | COL_2 | COL_3 |
 ----------------------------

我有一种情况需要更新上表,例如 -

Update <table_name>
set decode (FILE_TYPE,'ABC',COL_1,
                      'CDE',COL_2,
                      'EFG',COL_3) = 'Y'
where ID = 12345;

请注意,FILE_TYPE 列来自上游作业。如何在运行时选择列名?请帮忙。谢谢!

【问题讨论】:

    标签: sql oracle sql-update case


    【解决方案1】:

    您无法动态选择要更新的列,但您可以执行多个条件赋值,例如:

    update mytable
    set 
        col_1 = decode(file_type, 'ABC', 'Y', col_1),
        col_2 = decode(file_type, 'CDE', 'Y', col_2),
        col_3 = decode(file_type, 'EFG', 'Y', col_3)
    where id = 12345
    

    仅更新参数与目标值匹配的列 - 否则,将重新分配原始值(因此这是无操作)。

    使用case 表达式可能更容易理解:

    update mytable
    set 
        col_1 = case when file_type = 'ABC' then 'Y' else col_1 end,
        col_2 = case when file_type = 'CDE' then 'Y' else col_1 end,
        col_3 = case when file_type = 'EFG' then 'Y' else col_1 end,
    where id = 12345
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多