[英]how to replace the first “9” in a string with another character in postgresql database column?
我在“测试”表中有一列“ pnum”。 我想为每条记录将pnum中的前导“ 9”替换为“ *”。
testdb=# select * from test limit 5;
id name pnum
===========================================
1 jk 912312345
2 tt 9912333333
我希望pnum看起来像这样:
id name pnum
===========================================
1 jk *12312345
2 tt *912333333
我将如何在postgres中做类似的事情?
编辑1:
到目前为止,我已经尝试过类似的方法:
select id, name, '*' && substring(pnum FROM 2 FOR CHAR_LENGTH(pnum)-1 ) from test limit 3;
还尝试了以下方法:
select id, name, '*' || substring(pnum FROM 2 FOR CHAR_LENGTH(pnum)-1 ) from test limit 3;
没人工作过...
编辑2:
我想到了:
select id, name, '*'::text || substring(pnum FROM 2 FOR CHAR_LENGTH(pnum)-1 ) from test limit 3;
请参见函数regexp_replace(字符串文本,模式文本,替换文本[,标志文本]) 字符串函数和运算符
SELECT regexp_replace('9912333333', '^[9]', '*');
regexp_replace
----------------
*912333333
您可以为此使用Postgres的字符串操作功能。 在您的情况下,“子字符串”和“ Char_Length”
'*' || Substring(<yourfield> FROM 2 FOR CHAR_LENGTH(<yourfield>)-1) as outputfield
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.