Oracle: Using CTE with update clause

后端 未结 3 1353
梦谈多话
梦谈多话 2021-01-22 00:21

Can I make an update using common table expression in oracle database?

I am getting error ORA-00928: missing SELECT keyword when I am trying this:

3条回答
  •  醉梦人生
    2021-01-22 01:09

    Basing on another answer on correlated update of key-preserved view, here is another possible option to use CTE with update in Oracle SQL avoiding duplication of where clause:

    update (
        with cte as (select avg(salary) average_salary from instructor)
        select id, salary, cte.average_salary from instructor cross join cte
        where 
    )
    set salary = case
        when salary <= average_salary/2 then salary * 1.1 
        when salary <= average_salary then salary * 1.05 
        else salary * 1.03                                     
    end
    

    In case of self-join this can be simplified to CTE-less version:

    update (
        select id, salary, (select avg(salary) from instructor) average_salary 
        from instructor
        where 
    )
    set salary = case
        when salary <= average_salary/2 then salary * 1.1 
        when salary <= average_salary then salary * 1.05 
        else salary * 1.03                                     
    end
    

提交回复
热议问题