T-SQL上的顺序IP阻塞

时间:2015-03-23 13:52:18

标签: sql-server tsql

如何通过上面的T-SQL获取这些IP块?我尝试使用CTE阻止,但我没有做。你能建议怎么做吗?

编辑:我写错了。不是CTE,是

10.230.0.1
10.230.1.1
10.230.x.1
10.230.x.1
...
10.249.253.1
10.249.254.1
10.249.255.1

3 个答案:

答案 0 :(得分:2)

尝试使用计数表:

;WITH t0 AS (SELECT 0 n UNION ALL SELECT 0)
    ,t1 AS (SELECT 0 n FROM t0 a CROSS JOIN t0 b) 
    ,t2 AS (SELECT 0 n FROM t1 a CROSS JOIN t1 b) 
    ,t3 AS (SELECT 0 n FROM t2 a CROSS JOIN t2 b) 
    ,t (n) AS (SELECT -1 + ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM t3)
SELECT '10.' + CAST(t1.n AS NVARCHAR(3)) + '.' + CAST(t2.n AS NVARCHAR(3)) +'.1' AS IP
FROM t t1
CROSS JOIN t t2
WHERE t1.n BETWEEN 230 AND 249
ORDER BY t1.n, t2.n

答案 1 :(得分:0)

我创建了另一个解决方案。也许这对其他人有帮助。

    CREATE FUNCTION fnTblATMList 
    (   
       @From INT,
       @To INT
    )
    RETURNS @table TABLE (IP_Address NVARCHAR(50))
    AS
    BEGIN
        Declare @third int
        while (@From <= @To)
        BEGIN
        set @third = 1

            while (@third <= 255)
    BEGIN
        INSERT INTO @table 
        select '10.' + CONVERT(nvarchar(3), @From) + '.' + CONVERT(NVARCHAR(3), @third) +'.2'
        SET @third = @third + 1
    END
        SET @From = @From +1

        END
        RETURN
    END
    GO

答案 2 :(得分:0)

另一种方法

;with seg as (
    select
        0 num
    union all
    select
        num + 1
    from
        seg
    where 
        num < 255
)
select
    cast(seg1.num as varchar)
     + '.' + cast(seg2.num as varchar)
     + '.' + cast(seg3.num as varchar)
     + '.' + cast(seg4.num as varchar)
from 
    seg seg1, 
    seg seg2,
    seg seg3,
    seg seg4
where
    seg1.num = 10                      -- Really need to filter
    and seg2.num between 230 and 249   -- on at least two of these
--  and seg3.num = '0'                 -- or the query will run
    and seg4.num = 1                   -- for a very long time
order by
    seg1.num,
    seg2.num,
    seg3.num,
    seg4.num
option (maxrecursion 0)