como substituir várias seqüências juntos no Oracle
Pergunta
Eu tenho uma corda vindo de uma tabela como "pode ??não pagar {1}, como o pagamento {2} devido a {3}". Quero substituir {1} com algum valor, {2} com algum valor e {3} com algum valor.
É possível substituir todos os 3 em uma função substituir? ou há alguma maneira eu posso escrever diretamente consulta e obter valor substituído? Quero substituir essas seqüências no Oracle procedimento armazenado no string original é proveniente de um dos minha mesa eu estou apenas fazendo select nessa tabela
e, em seguida, eu quero substituir {1}, {2}, {3} valores dessa cadeia para o outro valor que eu tenho de outra tabela
Solução
Embora não seja uma chamada, você pode aninhar as chamadas replace()
:
SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval)
Outras dicas
Se há muitas variáveis ??para substituir e você tê-los em outra mesa e se o número de variáveis ??é variável, você pode usar uma CTE recursiva para substituí-los. Um exemplo abaixo. Em fg_rulez tabela que você colocar as cordas com a sua substituição. Em fg_data mesa você tem suas cadeias de entrada.
set define off;
drop table fg_rulez
create table fg_rulez as
select 1 id,'<' symbol, 'less than' text from dual
union all select 2, '>', 'great than' from dual
union all select 3, '$', 'dollars' from dual
union all select 4, '&', 'and' from dual;
drop table fg_data;
create table fg_Data AS(
SELECT 'amount $ must be < 1 & > 2' str FROM dual
union all
SELECT 'John is > Peter & has many $' str FROM dual
union all
SELECT 'Eliana is < mary & do not has many $' str FROM dual
);
WITH q(str, id) as (
SELECT str, 0 id
FROM fg_Data
UNION ALL
SELECT replace(q.str,symbol,text), fg_rulez.id
FROM q
JOIN fg_rulez
ON q.id = fg_rulez.id - 1
)
SELECT str from q where id = (select max(id) from fg_rulez);
Assim, um único replace
.
Resultado:
amount dollars must be less than 1 and great than 2
John is great than Peter and has many dollars
Eliana is less than mary and do not has many dollars
O símbolo terminologia em vez de variável vem esta pergunta duplicada.
A Oracle 11gR2
Se o número de valores para substituir é muito grande ou você precisa ser capaz de mantê-lo facilmente, você também pode dividir a string, use uma tabela de dicionário e, finalmente, agregar os resultados
No exemplo abaixo eu estou supondo que as palavras sua seqüência são separados com blankspaces eo wordcount na cadeia não será maior do que 100 (Pivot Table cardinalidade)
with Dict as
(select '{1}' String, 'myfirstval' Repl from dual
union all
select '{2}' String, 'mysecondval' Repl from dual
union all
select '{3}' String, 'mythirdval' Repl from dual
union all
select '{Nth}' String, 'myNthval' Repl from dual
)
,MyStrings as
(select 'This is the first example {1} ' Str, 1 strnum from dual
union all
select 'In the Second example all values are shown {1} {2} {3} {Nth} ', 2 from dual
union all
select '{3} Is the value for the third', 3 from dual
union all
select '{Nth} Is the value for the Nth', 4 from dual
)
,pivot as (
Select Rownum Pnum
From dual
Connect By Rownum <= 100
)
,StrtoRow as
(
SELECT rownum rn
,ms.strnum
,REGEXP_SUBSTR (Str,'[^ ]+',1,pv.pnum) TXT
FROM MyStrings ms
,pivot pv
where REGEXP_SUBSTR (Str,'[^ ]+',1,pv.pnum) is not null
)
Select Listagg(NVL(Repl,TXT),' ') within group (order by rn)
from
(
Select sr.TXT, d.Repl, sr.strnum, sr.rn
from StrtoRow sr
,dict d
where sr.TXT = d.String(+)
order by strnum, rn
) group by strnum
Vamos escrever a mesma amostra como um CTE apenas:
with fg_rulez as (
select 1 id,'<' symbol, 'less than' text from dual
union all select 2, '>', 'greater than' from dual
union all select 3, '$', 'dollars' from dual
union all select 4, '+', 'and' from dual
), fg_Data AS (
SELECT 'amount $ must be < 1 + > 2' str FROM dual
union all
SELECT 'John is > Peter + has many $' str FROM dual
union all
SELECT 'Eliana is < mary + do not has many $' str FROM dual
), q(str, id) as (
SELECT str, 0 id
FROM fg_Data
UNION ALL
SELECT replace(q.str,symbol,text), fg_rulez.id
FROM q
JOIN fg_rulez
ON q.id = fg_rulez.id - 1
)
SELECT str from q where id = (select max(id) from fg_rulez);
Se você está fazendo isso dentro de uma seleção, você pode simplesmente peça-lo juntos, se os seus valores de substituição são colunas, usando concatenação.