在SQL Server 2005 数据库设计时,为了查询效率,常常把点分十进制表示的ip地址设计为bigint类型。存储的时候,怎么把点分十进制转换为bigint,请参考下面的sql自定义函数:
- USE [temp]
- GO
- /****** 对象: UserDefinedFunction [dbo].[UF_CovertIPToInt] 脚本日期: 08/06/2012 16:55:22 ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
-
- -- =============================================
- -- Author: ----
- -- Create date: 2009-05-11
- -- Description: 转换ip
- -- =============================================
- CREATE FUNCTION [dbo].[UF_CovertIPToInt]
- (
- @ip varchar(20)
- )
- RETURNS bigint
- AS
- BEGIN
- declare @pos int
- declare @sub1 varchar(10)
- declare @sub2 varchar(10)
- declare @sub3 varchar(10)
- declare @sub4 varchar(10)
-
- set @pos = charindex(".",@ip)
-
- if(@pos<1) return 0
-
- set @sub1 = substring(@ip,0,@pos)
-
- --select @sub1
-
- set @ip = substring(@ip, @pos+1 ,len(@ip) - @pos + 1)
-
- --select @ip
-
- set @pos = charindex(".",@ip)
-
- if(@pos<1) return 0
-
- set @sub2 = substring(@ip,0,@pos)
-
- --select @sub2
-
- set @ip = substring(@ip, @pos+1 ,len(@ip) - @pos + 1)
-
- --select @ip
-
- set @pos = charindex(".",@ip)
-
- if(@pos<1) return 0
-
- set @sub3 = substring(@ip,0,@pos)
-
- --select @sub3
-
- set @ip = substring(@ip, @pos+1 ,len(@ip) - @pos + 1)
-
- if(len(@ip)<1) return 0
-
- select @sub4 = @ip
-
- --select @sub4
-
- return cast(@sub1 as bigint ) * 16777216 + cast(@sub2 as bigint ) * 65536 + cast(@sub3 as bigint )*256 + cast(@sub4 as bigint )
-
- END
有了上面的函数,我可以方便地进行转换,例如:
- select dbo.UF_CovertIPToInt("192.168.1.100") as ip
显示的时候,为了方便阅读,常常需要把bigint转换为点分十进制,请参考下面的自定义函数:
- USE [temp]
- GO
-
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
-
- CREATE FUNCTION [dbo].[UF_ConvertIPToStr]
- (
- @ip bigint
- )
- RETURNS varchar(20)
- AS
- BEGIN
- RETURN cast((@ip/16777216)% 256 as varchar(4)) + "." + cast( (@ip/65536)% 256 as varchar(4)) +"."+ cast( (@ip/256)%256 as varchar(4))+ "."+ cast( (@ip%256)as varchar(4))
-
- END
可以通过下面的方式调用该函数:
- select dbo.UF_ConvertIPToStr (3232235790) as ip
当然,对于mysql数据,就没必要这么麻烦了。完全可以使用内置的函数:inet_aton 和inet_ntoa
- select inet_aton("192.168.1.12");
- select inet_ntoa(3232235788);
MySQL复制详解Oracle Apps DBA工具:ADADMIN使用说明相关资讯 SQL Server SQL Server 2005
- SQL Server 2005不会再收到安全更 (05月06日)
- Build2016喜讯:Linux用户注册微软 (03月17日)
- SQL Server on Linux 理由浅析 (03月09日)
| - SQL Server 2005生命周期将于2016 (04月07日)
- 微软要抢甲骨文用户?从Oracle迁移 (03月13日)
- 微软发布面向Linux的SQL Server预 (03月08日)
|
本文评论 查看全部评论 (0)