我正在尝试将给定的IPv4地址拆分为四个数字。
在SQL Server中,此查询适用于我:
select CAST (PARSENAME('10.20.30.40',4) AS INT)
结果:10
select CAST (PARSENAME('10.20.30.40',3) AS INT)
结果:20
等等。
我需要Oracle SQL中的等效语法,但找不到它。有什么想法吗?
答案 0 :(得分:12)
您可以使用regexp_substr
:
select ip,
regexp_substr(ip, '\d+',1,1) as first_octet,
regexp_substr(ip, '\d+',1,2) as second_octet,
regexp_substr(ip, '\d+',1,3) as third_octet,
regexp_substr(ip, '\d+',1,4) as fourth_octet
from (select '10.20.30.40' AS ip from dual )ips;
<强> Rextester Demo 强>
答案 1 :(得分:4)
您可以使用比正则表达式快得多的简单字符串函数(INSTR
和SUBSTR
):
Oracle 11g R2架构设置:
CREATE TABLE sample_data ( ip_address ) AS
SELECT '10.20.30.40' FROM DUAL
查询1 :
SELECT TO_NUMBER(
SUBSTR( ip_address, 1, first_sep - 1 )
) AS ClassA,
TO_NUMBER(
SUBSTR( ip_address, first_sep + 1, second_sep - first_sep )
) AS ClassB,
TO_NUMBER(
SUBSTR( ip_address, second_sep + 1, third_sep - second_sep )
) AS ClassC,
TO_NUMBER(
SUBSTR( ip_address, third_sep + 1 )
) AS ClassD
FROM (
SELECT ip_address,
INSTR( ip_address, '.', 1, 1 ) AS first_sep,
INSTR( ip_address, '.', 1, 2 ) AS second_sep,
INSTR( ip_address, '.', 1, 3 ) AS third_sep
FROM sample_data
)
<强> Results 强>:
| CLASSA | CLASSB | CLASSC | CLASSD |
|--------|--------|--------|--------|
| 10 | 20 | 30 | 40 |
答案 2 :(得分:3)
如果您需要一个功能,这是另一个解决方案:
SELECT REGEXP_SUBSTR('10.20.30.40', '\d+', 1, LEVEL) as octet, level
FROM dual
CONNECT BY LEVEL <= 4;
OCTET LEVEL
10 1
20 2
30 3
40 4