sql IP地址 排序

来源:百度知道 编辑:UC知道 时间:2024/08/20 16:02:23
表iptable中存储:
10.130.4.34
10.28.4.34
10.125.4.34
我想得到的结果这样排序:
10.28.4.34
10.125.4.34
10.130.4.34
即以数值而非字串方式排序,有什么办法?

select *
from iptable
order by convert(numeric(20),replace(ip字段,'.',''))

--用一个函数转换IP后再排序
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_IP2Int]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_IP2Int]
GO

--1. 字符串IP地址转换成IP数值函数。
CREATE FUNCTION dbo.f_IP2Int(
@ip char(15)
)RETURNS bigint
AS
BEGIN
DECLARE @re bigint
SET @re=0
SELECT @re=@re+LEFT(@ip,CHARINDEX('.',@ip+'.')-1)*ID
,@ip=STUFF(@ip,1,CHARINDEX('.',@ip+'.'),'')
FROM(
SELECT ID=CAST(16777216 as bigint)
UNION ALL SELECT 65536
UNION ALL SELECT 256
UNION ALL SELECT 1)a
RETURN(@re)
END

go

use Tempdb
go
--> -->

declare @iptable table([Col1] nvarchar(11))
Insert @iptable