我在 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/