Вы можете использовать instr
, чтобы найти пробелы, и substr
, чтобы извлечь токены, с некоторой условной логикой:
-- CTE for your sample data
with users (name1) as (
select 'Benjamin Barker' from dual
union all select 'Alexis Jacob Alexander Cruise' from dual
union all select 'Christopher James Lee' from dual
union all select 'Madonna' from dual
)
-- actual query
select case
when instr(name1, ' ') = 0
then name1
else substr(name1, 1, instr(name1, ' ') - 1)
end
|| case
when instr(name1, ' ', 1, 2) > 0
then substr(name1, instr(name1, ' ', -1))
end
as result
from users;
RESULT
----------------------------------------------------------
Benjamin
Alexis Cruise
Christopher Lee
Madonna
Если вы действительно хотите ****
, как показано в вопросе, вы можете объединить его в первом предложении else
:
select case
when instr(name1, ' ') = 0
then name1
else substr(name1, 1, instr(name1, ' ') - 1) || ' ****'
end
|| case
when instr(name1, ' ', 1, 2) > 0
then substr(name1, instr(name1, ' ', -1))
end
as result
from users;
RESULT
---------------------------------------------------------------
Benjamin ****
Alexis **** Cruise
Christopher **** Lee
Madonna
или, если вы хотите добавить + Masked
, как вы сказали в комментарии, только к тем, которые действительно изменены, вы можете просто объединить третье выражение:
select case
when instr(name1, ' ') = 0
then name1
else substr(name1, 1, instr(name1, ' ') - 1)
end
|| case
when instr(name1, ' ', 1, 2) > 0
then substr(name1, instr(name1, ' ', -1))
end
|| case
when instr(name1, ' ', 1, 1) > 0
then ' + Masked'
end
as result
from users;
RESULT
-------------------------------------------------------------------
Benjamin + Masked
Alexis Cruise + Masked
Christopher Lee + Masked
Madonna
Если вы хотите использовать это в функции, просто используйте те же выражения:
create or replace function short_name (p_name varchar2)
return varchar2 as
begin
return case
when instr(p_name, ' ') = 0
then p_name
else substr(p_name, 1, instr(p_name, ' ') - 1)
end
|| case
when instr(p_name, ' ', 1, 2) > 0
then substr(p_name, instr(p_name, ' ', -1))
end
|| case
when instr(p_name, ' ', 1, 1) > 0
then ' + Masked'
end;
end short_name;
/
select short_name(name1) as result from users;
RESULT
------------------------------
Benjamin + Masked
Alexis Cruise + Masked
Christopher Lee + Masked
Madonna