如何使用 regexp_replace 替换字符串中使用 select 语句的字符?

How to use regexp_replace to replace a character in a string using the select statement?

以下是我的代码

select (upper(fname)||' '||upper(mname)||' '||upper(lname)) as customer_name,
(indv_corp_flag) as Customer_type,
(regexp_replace(passport_no,'D','B')"regexp_replace") as passport_no, 
(case when indv_corp_flag = 'C' then registration_no else null end) as registration_no,
(case when indv_corp_flag = 'I' then marital_status else null end) as Marital_status
from Nbfc_krishnan_m;

它给出了类似

的错误
ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"
*Cause:    
*Action:
Error at Line: 91 Column: 38

但在单独操作时它的工作方式类似于

select
regexp_replace(passport_no,'S','d')"regexp_replace" 
from nbfc_krishnan_m; 

执行成功

您已将投影的所有列括在不必要的括号中。它可以编译,但混乱使您看不到问题。没有这些括号,很明显你有一列有两个别名:

regexp_replace(passport_no,'D','B')"regexp_replace" as passport_no

您发布了一个有效的查询。它之所以有效,是因为它只有一个别名。因此解决方案很明显:

select upper(fname)||' '||upper(mname)||' '||upper(lname) as customer_name,
        indv_corp_flag as Customer_type,
        regexp_replace(passport_no,'D','B') as passport_no, 
        case when indv_corp_flag = 'C' then registration_no else null end as registration_no,
        case when indv_corp_flag = 'I' then marital_status else null end as Marital_status
from Nbfc_krishnan_m;

将来为实际需要它们的表达式保留括号。


" if the string is DCCFF12996 and I want output to be BCCFF12669"

您只是将一个字符替换为另一个字符,因此您应该使用标准 TRANSLATE() 函数。只有在需要正则表达式(即模式)时才使用 REGEXP_REPLACE() 。

SQL> select upper(fname||' '||mname||' '||lname) as customer_name,
  2     passport_no, 
  3     translate(passport_no,'D69','B96') as new_passport_no 
  4  from Nbfc_krishnan_m; 

CUSTOMER_NAME                     PASSPORT_N NEW_PASSPO
--------------------------------- ---------- ----------
FOX IN SOCKS                      ABCD123    ABCB123
DAISY HEAD MAYZIE                 DCCFF12996 BCCFF12669

SQL>