我有超过1000万条记录,其中包含SQL Server中的IP地址。我需要将地址解析为单独的列以进一步分析它们。我尝试使用PATINDEX,它只能覆盖一个IP地址模式。第一个八位字节必须是50,41或107.其他三个八位字节可以是从单个到三个数字。以下是我使用的50/41 / 107.xxx.xxx.xxx:
SELECT SUBSTRING(Column_1,PATINDEX('%[50|41|107].[0-9][0-9][0-9].[0-9][0-9][0-9].[0-9]%',Column_1)-2,14)
FROM table_1
如何在一个查询中捕获所有IP模式(50.x.xxx.xxx,50.xx.x.xxx等)?
答案 0 :(得分:2)
您可以使用PARSENAME
:
SELECT *
FROM dbo.YourTable
WHERE PARSENAME(YourColumn,4) = '50'
答案 1 :(得分:0)
使用Left
和Charindex
字符串功能。试试这个。
select * from table_1 where
left(Column_1,charindex('.',Column_1)-1) in('50','41','107')
答案 2 :(得分:0)
此查询将确保您只捕获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