mytext
是mytable
中包含值('ABC123','ABC456','Alphabet 123','Alphabet 456', 'DEF123' ...)
的列,但我希望将它们全部格式化为'ABC123'
。我无法正确使用语法
UPDATE mytable
SET mytext =
CASE
WHEN (mytext like 'Alphabet %') Then REPLACE(mytext, 'Alphabet ', 'ABC')
WHEN (mytext like 'Dookickey %') Then REPLACE(mytext, 'Doohickey ', 'DEF')
WHEN (mytext like 'Goofiness %') Then REPLACE(mytext, 'Goofiness ', 'GHI')
ELSE -- I want no other rows to be processed
END;
答案 0 :(得分:2)
只需使用:
UPDATE mytable SET mytext = REPLACE(mytext, 'Alphabet ', 'ABC')
如果没有匹配,那么REPLACE
工作将保持值不变。但是,这将触及表中的所有行,自行替换某些值 - 这至少不是非常有效。此外,这将取代世界Alphabet
的任何出现,即使不在字符串的开头。
如果您需要更强大的功能,则应添加过滤器:
UPDATE mytable SET mytext = REPLACE(mytext, 'Alphabet ', 'ABC')
WHERE mytext LIKE 'Alphabet %'
请参阅http://sqlfiddle.com/#!4/16512/1
在编辑问题以支持多个替换字符串时,您确实可以使用CASE
语句:
UPDATE mytable
SET mytext =
CASE
WHEN (mytext LIKE 'Alphabet %') THEN REPLACE(mytext, 'Alphabet ', 'ABC')
WHEN (mytext LIKE 'Dookickey %') THEN REPLACE(mytext, 'Dookickey ', 'DEF')
WHEN (mytext LIKE 'Goofiness %') THEN REPLACE(mytext, 'Goofiness ', 'GHI')
ELSE mytext
-- ^^^^^^
-- let unchanged
END;
请参阅http://sqlfiddle.com/#!4/31531c/1
与我的第一个解决方案一样,这将触及表格的所有行。和之前一样,您可以使用过滤器来避免这种情况。在这种情况下,不再需要ELSE
子句(因为不匹配的行保持不变):
UPDATE mytable
SET mytext =
CASE
WHEN (mytext LIKE 'Alphabet %') THEN REPLACE(mytext, 'Alphabet ', 'ABC')
WHEN (mytext LIKE 'Dookickey %') THEN REPLACE(mytext, 'Dookickey ', 'DEF')
WHEN (mytext LIKE 'Goofiness %') THEN REPLACE(mytext, 'Goofiness ', 'GHI')
END
WHERE mytext LIKE 'Alphabet %'
OR mytext LIKE 'Dookickey %'
OR mytext LIKE 'Goofiness %';
答案 1 :(得分:0)
您可以使用CASE语句中的SUBSTR函数来检查前N个字符。
您可能需要调整要比较的字符数:在此示例中,CASE将仅匹配前8个字符:
select CASE SUBSTR("FIELD1", 1, 8)
-- 12345678
WHEN 'OLD_TEXT' THEN REPLACE("FIELD1", 'OLD_TEXT', 'NEW_TEXT')
WHEN 'ALPHABET' THEN REPLACE("FIELD1", 'ALPHABET', 'ABC')
ELSE "FIELD1" -- For all other values, leave unchanged
END
from
(
select
'OLD_TEXT1' "FIELD1"
FROM DUAL
UNION
select
'OLD_TEXT2' "FIELD1"
FROM DUAL
UNION
select
'ALPHABET' "FIELD1"
FROM DUAL
UNION
select
'DNR1' "FIELD1"
FROM DUAL
UNION
select
'DNR2_DO_NOT_REPLACE' "FIELD1"
FROM DUAL
) ;