将给定范围的所有IP地址放入SQL Server表中

时间:2015-08-15 05:45:11

标签: sql-server sql-server-2008 sql-server-2012

我有IP地址,如&#;; 255.255.120.110-255.255.120.115,255.10.120.110-255.10.120.115,255.10.10.115'

我想插入表格。最后我需要如下结果:

   IPAddresses
    ---------------
    255.255.120.110
    255.255.120.111
    255.255.120.112
    255.255.120.113
    255.255.120.114
    255.255.120.115
    255.255.120.118
    255.255.120.120.......

1 个答案:

答案 0 :(得分:0)

IPAddress EX:'255.255.120.110-255.255.120.115,255.10.120.110-255.10.120.115,255.10.10.115'

insert into #IPAddresses(ColumnName)
        select * from [dbo].[splitFunction] (@IPAddresses,',')

        declare @IPStart int

        declare Cur_IPAddress cursor for 
        select substring(substring(Item, charindex('.', Item, charindex('.', Item, charindex('.', Item ) + 1) + 1)+1, len(Item)),1,
                charindex('-',substring(Item, charindex('.', Item, charindex('.', Item, charindex('.', Item ) + 1) + 1)+1, len(Item)))-1) IPStart ,
                substring(Item,1, charindex('.', Item, charindex('.', Item, charindex('.', Item ) + 1) + 1)) IPExt,
                reverse(substring(reverse(Item),1,charindex('.',reverse(Item))-1)) MaxIp
        from  #IPAddresses where charindex('-',Item)>0
        open Cur_IPAddress  
        fetch next from  Cur_IPAddress into @IPStart, @IPExt, @MaxIp
        while @@fetch_status = 0
        begin
            ;with X 
            as(
                select @IPStart Lev
                union all
                select X.Lev+1
                from X 
                where X.Lev < @MaxIp
            )  insert into #IPAddresses
        select @IPExt +cast(Lev as varchar) Item  from X option(maxrecursion 1000)

        fetch next from  Cur_IPAddress into @IPStart, @IPExt, @MaxIp
        end
        close Cur_IPAddress
        deallocate Cur_IPAddress

        delete from  #IPAddresses where charindex( '-', Item )>0
        --select * from #IPAddresses
    end