create or replace Function Last_Char(p_input_char VarChar2) RETURN VarChar2 Is
BEGIN
Declare
mChar VarChar2(1) := '';
mSfx VarChar2(20) := '';
Begin
If p_input_char Is Null Then
RETURN 'NO_PARAM_ERR';
End If;
--
mChar := SubStr(p_input_char, Length(p_input_char), 1);
If mChar = '0' Then
mSfx := '-ZERO';
ElsIf InStr('1,3,5,7,9', mChar) > 0 Then
mSfx := '-ODD';
ElsIf InStr('2,4,6,8', mChar) > 0 Then
mSfx := '-EVEN';
Else
mSfx := '-TEXT';
End If;
RETURN Upper(mChar) || mSfx;
End;
END Last_Char
...测试...
SET SERVEROUTPUT ON
Begin
DBMS_OUTPUT.PUT_LINE('jhkjd087');
DBMS_OUTPUT.PUT_LINE('jhkjd08');
DBMS_OUTPUT.PUT_LINE('jhkjd0');
DBMS_OUTPUT.PUT_LINE('jhkjd');
End;
-- Results
--
-- anonymous block completed
-- 7-ODD
-- 8-EVEN
-- 0-ZERO
-- D-TEXT
WITH tbl(ID, str) AS (
SELECT 1, 'abcd' FROM dual UNION ALL
SELECT 2, 'abc1' FROM dual UNION ALL
SELECT 3, 'abc2' FROM dual UNION ALL
SELECT 4, 'abc0' FROM dual UNION ALL
SELECT 5, NULL FROM dual UNION ALL
SELECT 6, 'abc'||CHR(09) FROM dual -- a tab
)
SELECT ID, str,
CASE
WHEN str IS NULL THEN
'NULL'
-- If last character is a zero
WHEN SUBSTR(str, '-1', '1') = '0' THEN
'0 - Zero'
-- If last character is an alpha character
WHEN REGEXP_LIKE(str, '.*[[:alpha:]]$') THEN
SUBSTR(str, '-1', '1') || ' - Text'
-- If last character is a number, test for even/odd by seeing if it's
-- evenly divisible by 2
WHEN REGEXP_LIKE(str, '.*[[:digit:]]$') THEN
CASE MOD(SUBSTR(str, '-1', '1'), 2)
WHEN 0 THEN SUBSTR(str, '-1', '1') || ' - Even'
WHEN 1 THEN SUBSTR(str, '-1', '1') || ' - Odd'
ELSE 'Something went horribly wrong'
END
-- Something not already caught. Non-printable character, show yourself!
ELSE 'Hex value - '|| RAWTOHEX(UTL_RAW.CAST_TO_RAW(SUBSTR(str, '-1', '1')))
END as last_char
FROM tbl;
ID STR LAST_CHAR
---- ---- ---------------
1 abcd d - Text
2 abc1 1 - Odd
3 abc2 2 - Even
4 abc0 0 - Zero
5 NULL
6 abc Hex value - 09
6 rows selected.
2条答案
按热度按时间siotufzp1#
尝试此操作-它将根据类型将后缀(“-TEXT”、“-ZERO”、“-ODD”、“-EVEN”)之一放在输入参数的最后一个字符...
...测试...
ds97pgxw2#
只是为了好玩这里有一个在查询中执行此操作的解决方案。(这是一个为你的问题提供样本数据的好方法)。总是在你的测试数据中放入意想不到的值。特别是当数据源是用户输入的数据时。它们可以并且将会命中你所能想象到的任何疯狂的键组合。注意你不能在case语句中使用if语句。此外,作为最佳实践,始终在case语句中捕获意外值。