Sql正则的使用

背景

有个需求需要将数据库的字符串后面一到四位的文本去掉文本格式是(-1到-999),因此想到使用正则表达式取出来这批语句,因为不是固定长度因此选用动态获取长度去replace数据。

因为采用的是异构数据库,因此下面提供了oracle和pgsql的逻辑

步骤一:根据正则取目标值

oracle

regexp_like(t.address_desc,'-[0-9]{1,3}$')

pgsql

t.address_desc ~ '-[0-9]{1,3}$'

步骤二:获取目标结尾数据

oracle

REGEXP_SUBSTR(t.address_desc,'-[0-9]{1,3}$')

pgsql

substring(address_desc from '-[0-9]{1,3}$')

步骤三:截取想要的字符串

oracle

select substr(t.address_desc,1,length(t.address_desc)-length(REGEXP_SUBSTR(t.address_desc,'-[0-9]{1,3}$')))

pgsql

select substring(address_desc, 1, length(address_desc)-length(substring(address_desc from '-[0-9]{1,3}$')))

完整sql

oracle

select substr(t.address_desc,1,length(t.address_desc)-length(REGEXP_SUBSTR(t.address_desc,'-[0-9]{1,3}$')))
  from aaa.address_desc_temp t
 where  regexp_like(t.address_desc,'-[0-9]{1,3}$');

pgsql

select
 substring(address_desc, 1, length(address_desc)-length(substring(address_desc from '-[0-9]{1,3}$'))),
 address_desc
from
 aaa.address_desc_temp t
where
 t.address_desc ~ '-[0-9]{1,3}$';

你可能感兴趣的:(小技巧合集,sql)