SQL Server:选择Ips表单Ips范围

时间:2016-02-08 21:53:06

标签: sql sql-server regex database

我对SQL很陌生,我对此表示赞同:

我有非常简单的SQL查询,但我需要修改该查询,以便从IP范围IP_ADDRESS100.64.0.0 – 100.127.255.255中仅选择10.0.0.0 – 10.255.255.255。我知道我需要使用正则表达式,但不知道如何?你能帮帮我吗?

原始查询:

SELECT 
    sal.IP_ADDRESS, sal.COUNTRY_CODE, sal.EVENT_ID, p.name, p.PARTNER_ID
FROM 
    EVENTS_USER.STREAM_ACCESS_LOGS sal, EVENTS_USER.STREAM_USERS su, EVENT_USER.PARTNERS p
WHERE 
    su.PARTNER_ID = p.PARTNER_ID
    AND sal.SUCESS = 'Y'
    AND sal.COUNTRY_CODE is null;

这个正则表达式看起来像那样吗?:

SELECT * FROM EVENTS_USER.STREAM_ACCESS_LOGS(
select regexp_replace(regexp_replace('100.64.0.0', '(\d+)', '00\1'), '0*(\d{3})', '\1')  IP_ADDRESS from dual 
UNION ALL 
select regexp_replace(regexp_replace('100.127.255.255', '(\d+)', '00\1'), '0*(\d{3})', '\1') from dual
) ORDER BY IP_ADDRESS; 

1 个答案:

答案 0 :(得分:0)

在MySQL中,我们有INET_ATON() function,它将地址转换为32位整数。 This answer另一个问题(不确定这是否符合重复版本?)提供了一些等效的SQL Server代码:

create function INET_ATON (@addr varchar(15))
returns bigint
with schemabinding
as
begin
  return
    cast(parsename(@addr, 4) as bigint) * 16777216 +
    cast(parsename(@addr, 3) as bigint) * 65536 +
    cast(parsename(@addr, 2) as bigint) * 256 +
    cast(parsename(@addr, 1) as bigint)
end

然后您可以将其添加到您的查询中:

SELECT 
    sal.IP_ADDRESS, sal.COUNTRY_CODE, sal.EVENT_ID, p.name, p.PARTNER_ID
FROM 
    EVENTS_USER.STREAM_ACCESS_LOGS sal, EVENTS_USER.STREAM_USERS su, EVENT_USER.PARTNERS p
WHERE 
    su.PARTNER_ID = p.PARTNER_ID
    AND sal.SUCESS = 'Y'
    AND sal.COUNTRY_CODE is null
    AND (
        INET_ATON(sal.IP_ADDRESS) BETWEEN INET_ATON("100.64.0.0") AND INET_ATON("100.127.255.255") OR
        INET_ATON(sal.IP_ADDRESS) BETWEEN INET_ATON("10.0.0.0") AND INET_ATON("10.255.255.255")
    )