我正在尝试使用' SWITCHED'来使用Oracle SQL更新语句。案例陈述如下所述:
update MY_TABLE SET STATE_ABBREVIATION=
(CASE STATE
WHEN 'MAHARASHTRA' THEN 'MH'
WHEN 'ASSAM' THEN 'AS'
WHEN 'HIMACHAL%' THEN 'HP'
...
ELSE
STATE
END
);
我从线程SQL - WHERE clause on each SET command in UPDATE?
中得到了这个线索问题是通配符字段未按预期运行。州列可能会像“喜马偕尔邦”这样的价值观。以及' HimachalPradesh'。
我还搜索了https://community.oracle.com/thread/290198,其中一个答案是使用了 搜索案例'哪个工作正常.. ..
CASE
(WHEN STATE LIKE 'ANDHRA%' THEN 'AP'
WHEN STATE LIKE 'HIMACHAL%' THEN 'HP'
END
我们如何在SWITCHED案例风格中实现这一目标? 我也试过
update MY_TABLE SET STATE_ABBREVIATION=
(CASE STATE
WHEN 'MAHARASHTRA' THEN 'MH'
WHEN 'ASSAM' THEN 'AS'
WHEN LIKE 'HIMACHAL%' THEN 'HP'
...
ELSE
STATE
END
);
这也行不通。
(SQL错误:ORA-00905:缺少关键字 00905. 00000 - "缺少关键字")。
答案 0 :(得分:1)
在所有情况下,您都必须使用搜索到的版本。
答案 1 :(得分:0)
您可以在所有条件中使用LIKE
,因为= 'aaaa'
和LIKE 'aaaa'
在输出方面没有区别
update MY_TABLE SET STATE_ABBREVIATION=
(CASE
WHEN STATE LIKE 'MAHARASHTRA' THEN 'MH'
WHEN STATE LIKE 'ASSAM' THEN 'AS'
WHEN STATE LIKE 'HIMACHAL%' THEN 'HP'
...
ELSE
STATE
END
);
答案 2 :(得分:0)
在CASE表达式中使用=
和LIKE
运算符应该没有任何问题。
例如,
表格强>
SQL> CREATE TABLE t AS SELECT * FROM(
2 WITH DATA(state) AS(
3 SELECT 'MAHARASHTRA' FROM dual UNION ALL
4 SELECT 'ASSAM' FROM dual UNION ALL
5 SELECT 'HIMACHAL PRADESH' FROM dual UNION ALL
6 SELECT 'ANDHRA PRADESH' FROM dual
7 )
8 SELECT * FROM DATA);
Table created.
SQL> SELECT * FROM t;
STATE
----------------
MAHARASHTRA
ASSAM
HIMACHAL PRADESH
ANDHRA PRADESH
SQL>
CASE声明
SQL> SELECT CASE
2 WHEN state = 'MAHARASHTRA' THEN 'MH'
3 WHEN state = 'ASSAM' THEN 'AS'
4 WHEN state LIKE 'HIMACHAL%' THEN 'HP'
5 ELSE state
6 END
7 FROM t;
CASEWHENSTATE='M
----------------
MH
AS
HP
ANDHRA PRADESH
更新语句
SQL> UPDATE t
2 SET state = (
3 CASE
4 WHEN state = 'MAHARASHTRA' THEN 'MH'
5 WHEN state = 'ASSAM' THEN 'AS'
6 WHEN state LIKE 'HIMACHAL%' THEN 'HP'
7 ELSE state
8 END
9 );
4 rows updated.
测试用例
SQL> select * from T;
STATE
----------------
MH
AS
HP
ANDHRA PRADESH
SQL>
因此,更新成功完成。