首页 > > > SQL解惑-如何从字符串中获取IP地址
SQL问题:请查询hsql.c_ip表中客户的IP地址,显示格式:cons_id,ip(IP地址示例: 192.168.1.1)
客户IP信息表 (hsql.c_ip) ,表结构及测试数据:
commit;
2016年全国部分企业进行了Oracle SCN隐患治理工作,SCN隐患主要是由于DBLINK “污染”造成,梳理Oracle数据库DBLINK使用逻辑成为了主要工作之一,方法之一就是整理dba_db_links 表HOST字段中记录的对端IP地址,如何从HOST记录的字符串中提取对端IP地址,成为需要解决的问题?
select c_ip,
--instr(c_ip, '#', 1, 1),
--instr(c_ip, '#', 1, 2),
substr(c_ip,
instr(c_ip, '#', 1, 1) + 1,
instr(c_ip, '#', 1, 2) - instr(c_ip, '#', 1, 1) - 1)
from hsql.c_ip;
select c_ip,
instr(c_ip, '#', 1, 1),
instr(c_ip, '#', -1),
substr(
c_ip,instr(c_ip, '#', 1, 1)+1,instr(c_ip, '#', -1)-instr(c_ip, '#', 1, 1)-1
),
--instr(c_ip, '#', 1, 2),
from hsql.c_ip;
select c.cons_id,
substr(substr(c_ip, instr(c_ip, '#') + 1, length(c_ip)),
0,
instr(substr(c_ip, instr(c_ip, '#') + 1, length(c_ip)), '#') - 1) ip
from hsql.c_ip c;
select c_ip,substr(c_ip,c_start+1,c_end-c_start-1),c_start,c_end from (
select c_ip,instr(c_ip,'#',1,1) c_start,instr(c_ip,'#',1,2) c_end from hsql.c_ip
);
select t.c_ip,regexp_substr(t.c_ip,'[1-9]*[.][1-9]*[.][0-9]*[.][1-9]*') c_IP from hsql.c_ip t;
select t.c_ip,regexp_substr(t.c_ip,'([0-9]*[.]){3}[1-9]*') c_IP from hsql.c_ip t;
select t.c_ip,regexp_substr(t.c_ip,'(\d*[.]){3}\d*') c_IP from hsql.c_ip t;
函数:
create or replace function getIp(v_ip in varchar2) return varchar2 is
Result varchar2(200);
begin
select regexp_substr(v_ip,'(\d*[.]){3}\d*') into Result from dual;
return(Result);
end getIp;
测试方法:
select p.cons_id, p.c_ip,getip(p.c_ip) from hsql.c_ip p where p.cons_id=1000002;
create view hsql.v_c_ip as
select p.cons_id cons_id,p.c_ip c_ip,regexp_substr(p.c_ip,'(\d*[.]){3}\d*') ip from hsql.c_ip p;
测试方法:
select tt.cons_id, tt.ip from hsql.v_c_ip tt;
如何您还有更好的方法,请给我们留言,期待您的回复!!!!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31442014/viewspace-3152660/ ,如需转载,请注明出处,否则将追究法律责任。