带CASE的SQL更新

时间:2017-10-12 10:37:20

标签: sql oracle sql-update

你能帮我解决一下这个SQL吗?

UPDATE VERSION
SET VERSION_STATUS_ID = IF((SELECT COUNT(*) from VERSION where KEY = 'ABC') > 1, 5, 6)
WHERE VERSION_ID = 1;

错误报告 -

  

SQL错误:ORA-00907:缺少右括号   00907. 00000 - “缺少右括号”

由于

3 个答案:

答案 0 :(得分:1)

使用CASE表达式:

UPDATE VERSION
SET VERSION_STATUS_ID = CASE WHEN (SELECT COUNT(*) from VERSION where KEY = 'ABC') > 1
                             THEN 5 ELSE 6 END
WHERE VERSION_ID = 1;

答案 1 :(得分:0)

EXISTS通常比子查询中的COUNT(*)更有效。如果表中有唯一的id列,则可以使用:

UPDATE VERSION v
    SET VERSION_STATUS_ID = (CASE WHEN EXISTS (SELECT 1 
                                               FROM VERSION v2
                                               WHERE v2.KEY = 'ABC' AND
                                                     v2.VERSION_ID <> v.VERSION_ID
                                              ) > 1
                                  THEN 5 ELSE 6
                             END)
WHERE VERSION_ID = 1;

这假定VERSION_ID是唯一的。如果您没有这样明确声明的列,则可以改为使用ROWID

答案 2 :(得分:0)

尝试一下效果很好

  SET SERVEROUTPUT ON;

DECLARE
 EXPE NUMBER;
 SAL NUMBER;
BEGIN


 SELECT TRUNC((SYSDATE - hire_date) / 365)  INTO EXPE
 FROM EMPLOYEES 
 WHERE EMPLOYEE_ID = 155;   


 UPDATE  EMPLOYEES 
 SET SALARY = CASE 
 WHEN   EXPE > 15 THEN SALARY+(SALARY*20/100)
 WHEN   EXPE < 15 THEN SALARY+(SALARY*30/100)
 ELSE 0
 END;

 SELECT SALARY INTO SAL
 FROM EMPLOYEES 
 WHERE EMPLOYEE_ID =155;

 DBMS_OUTPUT.PUT_LINE('THIS IS THE SALARY ' || '  ' ||SAL || ' ' || ' AND THIS IS THE EXPERINCE '||EXPE);
END;