此查询将确保您仅捕获只有 4 个八位字节的 IP 地址。
所有八位字节都需要在指定的范围内(当前设置为 0-255,但可以在 where 子句中更改)您还可以将 BETWEEN a AND b 更改为 IN (a, b, ...),它只会捕获那些特定的数字。
它还将它们自己列中的八位位组作为整数返回,这将是存储它们向前移动的好方法,以防您需要对特定范围进行分析,那么您将来不需要解析文本。
注意:由于使用了 TRY_CAST,这仅适用于 SQL Server 2012 和
WITH Octet_Position (column_1, position_1, position_2, position_3)
AS
(
SELECT
column_1,
CHARINDEX('.', column_1),
CHARINDEX('.', column_1, CHARINDEX('.', column_1) + 1),
CHARINDEX('.', column_1, (CHARINDEX('.', column_1, CHARINDEX('.', column_1) + 1)) + 1)
FROM Table_1
)
SELECT
column_1 AS ip_address,
TRY_CAST(SUBSTRING(column_1, 0, position_1) AS INT) AS octet_1,
TRY_CAST(SUBSTRING(column_1, position_1 + 1, position_2 - position_1 - 1) AS INT) AS octet_2,
TRY_CAST(SUBSTRING(column_1, position_2 + 1, position_3 - position_2 - 1) AS INT) AS octet_3,
TRY_CAST(SUBSTRING(column_1, position_3 + 1, LEN(column_1) - position_3) AS INT) AS octet_4
FROM Octet_Position
WHERE
--make sure there are three .'s
position_1 > 0 AND
position_2 > 0 AND
position_3 > 0 AND
--Make sure the octets are numbers
TRY_CAST(NULLIF(SUBSTRING(column_1, 0, position_1), '') AS INT) IS NOT NULL AND
TRY_CAST(NULLIF(SUBSTRING(column_1, position_1 + 1, position_2 - position_1 - 1), '') AS INT) IS NOT NULL AND
TRY_CAST(NULLIF(SUBSTRING(column_1, position_2 + 1, position_3 - position_2 - 1), '') AS INT) IS NOT NULL AND
TRY_CAST(NULLIF(SUBSTRING(column_1, position_3 + 1, LEN(column_1) - position_3), '') AS INT) IS NOT NULL AND
--make sure the octects are in the correct range
TRY_CAST(NULLIF(SUBSTRING(column_1, 0, position_1), '') AS INT) BETWEEN 0 AND 255 AND
TRY_CAST(NULLIF(SUBSTRING(column_1, position_1 + 1, position_2 - position_1 - 1), '') AS INT) BETWEEN 0 AND 255 AND
TRY_CAST(NULLIF(SUBSTRING(column_1, position_2 + 1, position_3 - position_2 - 1), '') AS INT) BETWEEN 0 AND 255 AND
TRY_CAST(NULLIF(SUBSTRING(column_1, position_3 + 1, LEN(column_1) - position_3), '') AS INT) BETWEEN 0 AND 255