如何在 SQL 服务器中将 IPv6 地址从十进制数字字符串转换为两个 bigints?

How to convert an IPv6 address from decimal number string to two bigints in SQL Server?

我有一个包含 IPv6 地址的 CSV 文件,我正试图将其批量导入 sql 服务器 table。 CSV 文件中的地址示例可能是“55828295930114724823525874468560830464”。我希望将 IP 地址存储到数据库中的两个 bigint 中,因为 SQL bigint 只能处理 64 位,而 IPv6 地址需要 128 位。我用于处理 IPV4 地址的导入代码是:

SET @sql = '
    INSERT INTO dbo.IPCountry
    SELECT
        REPLACE(ipFROM, ''"'', '''') AS ipFROM,
        REPLACE(ipTO, ''"'', '''') AS ipTO,
        CAST(REPLACE(countrySHORT, ''"'', '''') AS CHAR(2)) AS countrySHORT
    FROM OPENROWSET(
        BULK ''' + @Directory + 'IPCountry.csv'',
        FORMATFILE = ''' + @Directory + 'IPCountry.Xml''
    ) AS t1
';
exec sp_executesql @sql;

如何将 128 位 IPv6 值转换为两个 bigint 值?

基于您的示例恰好是一个 38 位数字字符串,我会将其分成两半并将每一半转换为 BIGINT 组件。

这是一个演示该过程并将其逆转的示例:

-- Prepare test variables
DECLARE @Source AS NVARCHAR(38)
DECLARE @ipFROMa AS BIGINT
DECLARE @ipFROMb AS BIGINT
DECLARE @Destination AS NVARCHAR(38)

SET @Source = '55828295930114724823525874468560830464'

-- Split Source into TWO strings and then each into a BIGINT
SET @ipFROMa = (SELECT CAST(SUBSTRING(@Source,1,19) AS BIGINT))
SET @ipFROMb = (SELECT CAST(SUBSTRING(@Source,20,19) AS BIGINT))

-- Test returning BIGINTs into one IPv6 string
SET @Destination = (SELECT 
                        CAST( 
                            CAST(@ipFROMa AS NVARCHAR(19)) +
                            CAST(@ipFROMb AS NVARCHAR(19))
                             AS nvarchar(38)))

-- Display the values for verification
SELECT @Source, @ipFROMa, @ipFROMb, @Destination

结果:

55828295930114724823525874468560830464 5582829593011472482 3525874468560830464 55828295930114724823525874468560830464