SQL Server:更新表将Int转换为IP字符串

时间:2017-08-21 07:48:00

标签: sql sql-server sql-server-2008

我的示例table1

有问题
Name                     IP                         OS        Version
----------------------------------------------------------------------
Jonh        0x20010db80a0b12f00000000000000001      Os         8.184
BoB         0x20010db80a0b12f00000000000000092      WIN        10.844
Alice       0x20010db80a0b12f00000000000000051     Linux       Ubuntu

我需要将IP列(varbinary)转换或更新为字符串。我尝试像这样更新整个表:

declare @IP as int  
set @IP =  * from 

select * 
from TABLE1,IP

UPDATE [dbo].[TABLE1]
SET IP = CONVERT(VARCHAR(3), (@IP/16777216) & 255) + '.'
         + CONVERT(VARCHAR(3), (@IP/65536) & 255) + '.'
         + CONVERT(VARCHAR(3), (@IP/256) & 255) + '.'
         + CONVERT(VARCHAR(3), @IP & 255) AS IP

但它不起作用。此类声明仅适用于一行/ IP,但不会更新整个表。

我的原始表有超过1000行。

2 个答案:

答案 0 :(得分:1)

如果您的转换逻辑正确,请尝试以下代码

  /*  create table table1
([name] varchar(100), [ip] varCHAR(100),[os] varchar(100),[version] varchar(100));
insert into table1 values
('Jonh',        '0x20010db80a0b12f00000000000000001'      ,'Os',         '8.184')
,('BoB',         '0x20010db80a0b12f00000000000000092'      ,'WIN',        '10.844')
,('Alice',    '0x20010db80a0b12f00000000000000051'     ,'Linux',       'Ubuntu');*/

select 
   Name,
   IP= 
    convert(varchar(3), (cast(IP AS VARBINARY(100))/16777216) & 255) + '.'

    + convert(varchar(3), (cast(IP AS VARBINARY(100))/65536) & 255) + '.'

    + convert(varchar(3), (cast(IP AS VARBINARY(100))/256) & 255) + '.'

    + convert(varchar(3), cast(IP AS VARBINARY(100)) & 255),
  OS,
  Version
from  TABLE1

See demo link

答案 1 :(得分:0)

应该就像这样

UPDATE [dbo].[TABLE1]
 SET IP =     
  convert(varchar(3), (IP/16777216) & 255) + '.'
    + convert(varchar(3), (IP/65536) & 255) + '.'
    + convert(varchar(3), (IP/256) & 255) + '.'
    + convert(varchar(3), IP & 255)

编辑: 在分割之前转换为varbinary然后转换为bigint,然后将结果转换为varchar

CONVERT(VARCHAR(3), CONVERT(BIGINT, CONVERT(VARBINARY, IP)) / 16777216 & 255)