Remove Leading Zeros On Ip Address in SQL

2019-09-01 06:10发布

问题:

I have a column called IP with data such as 10.001.99.108

I want to run a script to change it to look like 10.1.99.108

I have used this before:

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

but that removes leading zeros at the begging.

Im not sure how I could change it to do the second segment.

回答1:

You can do this with parsename() and a method to remove the leading zeros. The following removes the leading zeros by casting to an integer and then back to string:

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))
       )


回答2:

try this solution

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

output result

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


标签: sql tsql replace