sql - 将 IP 地址范围导入数据库表 - 如何检查 T-SQL 中的范围冲突?

标签 sql sql-server t-sql ip-address

我在 SQL Server 数据库中有一个表,用于存储起始和结束数字 IP 地址值(不是 IPv4)。我将向该表中导入其他 IP 地址范围。在实际导入之前,有谁知道如何使用 T-SQL 检查要导入的任何范围是否与任何现有范围冲突?谢谢。

最佳答案

给定一个类似的表格

 create table IPRanges (
      IPStart int not null unique nonclustered
     ,IPEnd   int not null unique nonclustered
     --other fields
  )

然后这里的函数将执行所需的测试。如果需要,可以将 TOP 1 添加到选择中。

create function dbo.ConflictingRanges(@IPStart int, @IPEnd int)
returns table return(
    select IPStart, IPEnd
    from dbo.IPRanges
    where IPStart <= @IPEnd
      and IPEnd   >= @IPStart
)

以下测试用例

insert dbo.IPRanges(IPStart,IPEnd)
values (2,4)
      ,(8,10)
      ,(15,20)
;

with trials as (
    select * from (values
         ( 0, 1)
        ,( 3, 5)
        ,( 9, 9)
        ,(19,21)
        ,(25,30)
        ,( 1,35)
    )trials(IPStart,IPEnd)
)
select 
     trials.IPStart
    ,trials.IPEnd
    ,data.IPStart as conflictStart
    ,data.IPEnd   as ConflictEnd
from trials
outer apply dbo.ConflictingRanges(trials.IPStart,trials.IPEnd) data;

产量:

IPStart     IPEnd       conflictStart ConflictEnd
----------- ----------- ------------- -----------
0           1           NULL          NULL
3           5           2             4
9           9           8             10
19          21          15            20
25          30          NULL          NULL
1           35          2             4
1           35          8             10
1           35          15            20

如果需要,可以通过返回 count(*) 而不是实际的冲突值来转换为 bool 结果。

关于sql - 将 IP 地址范围导入数据库表 - 如何检查 T-SQL 中的范围冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193463/

相关文章:

c# - 将 .net decimal 类型转换为 tsql decimal(3,3)

sql-server - 根据列类型声明变量类型

sql-server - 删除 DDL 触发器会出现错误

SQL 自连接查询帮助

c# - 带有多表插入的 EntityFramework 事务回滚

sql - 可选 where 子句 jasper 报告

mysql - 比较 varchar 与 sql 查询中的数字

mysql - 如何修复此 MYSQL 查询

sql - 按日期顺序排列的 T-SQL 查询组(间隙和孤岛)

sql - TSQL - 如果组内不存在特定条目,则插入条目