在SQL中删除Ip地址上的前导零

时间:2015-01-20 11:51:54

标签: sql tsql replace

我有一个名为IP的列,其中包含10.001.99.108

等数据

我想运行一个脚本来将其更改为10.1.99.108

我以前用过这个:

update TABLE set IP =  substring(IP, patindex('%[^0]%',IP), 10) 

但是这会在乞讨时删除前导零。

我不知道如何更改它以进行第二段。

2 个答案:

答案 0 :(得分:5)

您可以使用parsename()和删除前导零的方法执行此操作。以下通过强制转换为整数然后返回字符串来删除前导零:

select (cast(cast(parsename(ip, 4) as int) as varchar(255)) +
        cast(cast(parsename(ip, 3) as int) as varchar(255)) +
        cast(cast(parsename(ip, 2) as int) as varchar(255)) +
        cast(cast(parsename(ip, 1) as int) as varchar(255))
       )

答案 1 :(得分:0)

尝试此解决方案

DECLARE @IpAdress AS TABLE ( IP VARCHAR(100) )
INSERT  @IpAdress
        ( IP )
VALUES  ( '10.001.99.108' ),
        ( '010.001.099.008' ),
        ( '080.081.999.008' );
WITH    Tally
          AS ( SELECT   n = 1
               UNION ALL
               SELECT   n + 1
               FROM     Tally
               WHERE    n <= 100
             ),
        split
          AS ( SELECT   i.IP ,
                        CONVERT(INT, ( CASE WHEN CHARINDEX('.', S.string) > 0
                                            THEN LEFT(S.string,
                                                      CHARINDEX('.', S.string)
                                                      - 1)
                                            ELSE string
                                       END )) AS part
               FROM     @IpAdress AS i
                        INNER JOIN Tally AS T ON SUBSTRING('.' + IP, T.N, 1) = '.'
                                                 AND T.N <= LEN(i.IP)
                        CROSS APPLY ( SELECT    String = ( CASE
                                                              WHEN T.N = 1
                                                              THEN LEFT(i.IP,
                                                              CHARINDEX('.',
                                                              i.IP) - 1)
                                                              ELSE SUBSTRING(i.IP,
                                                              T.N, 1000)
                                                           END )
                                    ) S
             )
    SELECT DISTINCT
            o.ip ,
            SUBSTRING(( SELECT  '.' + CONVERT(VARCHAR, i.part)
                        FROM    split AS i
                        WHERE   i.ip = o.ip
                      FOR
                        XML PATH('')
                      ), 2, 1000) AS newIP
    FROM    split AS o

输出结果

ip                    newIP
010.001.099.008       10.1.99.8
080.081.999.008       80.81.999.8
10.001.99.108         10.1.99.108