用 SQL 語法查詢符合條件範圍的 IP

用 SQL 語法查詢符合條件範圍的 IP

  1. CREATE FUNCTION IP2INT( @ip nvarchar( 15 ) ) RETURNS bigint AS
  2. BEGIN
  3. DECLARE @number bigint
  4. SET @number = 0
  5. SELECT @number = @number +
  6. LEFT ( @ip, CHARINDEX( '.', @ip + '.' ) -1 ) * t,
  7. @ip = STUFF(@ip, 1, CHARINDEX( '.', @ip + '.' ), '' )
  8. FROM
  9. (
  10. SELECT t = CAST( 16777216 AS bigint)
  11. UNION ALL SELECT 65536
  12. UNION ALL SELECT 256
  13. UNION ALL SELECT 1
  14. ) AS T
  15. RETURN (@number)
  16. END
  17. GO
  18. DECLARE @IPTable TABLE (ip nvarchar( 15 ) )
  19. INSERT INTO @IPTable VALUES ( N'172.16.57.103' )
  20. INSERT INTO @IPTable VALUES ( N'172.16.58.103' )
  21. INSERT INTO @IPTable VALUES ( N'172.16.59.103' )
  22. INSERT INTO @IPTable VALUES ( N'172.16.60.103' )
  23. INSERT INTO @IPTable VALUES ( N'172.16.61.103' )
  24. INSERT INTO @IPTable VALUES ( N'172.16.62.103' )
  25. SELECT ip
  26. FROM @IPTable
  27. WHERE dbo.IP2INT(ip)
  28. BETWEEN dbo.IP2INT( '172.16.58.1' ) AND dbo.IP2INT( '172.16.60.1' )