Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get only IP Address from given string

I have the following given string formats.

DECLARE @IPData_1 nvarchar(max) = '{"ODBC":"Connection-StringIPX-IP=10.60.96.230&X-Local}'
DECLARE @IPData_2 nvarchar(max) = '{"ODBC":"Connection-StringIPX-IP:1.60.0.230X-Local=1}'
DECLARE @IPData_3 nvarchar(max) = '{"ODBC":"Connection-StringIPX-For=233.60.255.120TransactionID:2}'
DECLARE @IPData_4 nvarchar(max) = '{"ODBC":"Connection-StringIPX-For:1.1.1.90ID=1}'

I want to get only IP Address that is:

10.60.96.230
1.60.0.230
233.60.255.120
1.1.1.90

My try:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT SUBSTRING(@IPData_1,CHARINDEX('IPX-IP=',@IPData_1)+7,CHARINDEX('.',@IPData_1)),
        SUBSTRING(@IPData_1,CHARINDEX('IPX-IP:',@IPData_1)+7,CHARINDEX('.',@IPData_1)),
        SUBSTRING(@IPData_1,CHARINDEX('IPX-For=',@IPData_1)+7,CHARINDEX('.',@IPData_1)),
        SUBSTRING(@IPData_1,CHARINDEX('IPX-For:',@IPData_1)+7,CHARINDEX('.',@IPData_1))

>Solution :

SQL Server is not the optimal place to perform string manipulation.

Having said that, sometimes we don’t have the option to do so elsewhere.

DECLARE @Table TABLE (IPData NVARCHAR(100));
INSERT INTO @Table (IPData) VALUES
('{"ODBC":"Connection-StringIPX-IP=10.60.96.230&X-Local}'),
('{"ODBC":"Connection-StringIPX-IP:1.60.0.230X-Local=1}'),
('{"ODBC":"Connection-StringIPX-For=233.60.255.120TransactionID:2}'),
('{"ODBC":"Connection-StringIPX-For:1.1.1.90ID=1}');      

SELECT IPData, SUBSTRING(IPData, PATINDEX('%[IP|FOR][:|=]%', IPData)+2, PATINDEX('%[0-9][&|X|T|ID]%', IPData)-(PATINDEX('%[IP|FOR][:|=]%', IPData))-1) AS IPData
  FROM @Table;
IPData IPData
{"ODBC":"Connection-StringIPX-IP=10.60.96.230&X-Local} 10.60.96.230
{"ODBC":"Connection-StringIPX-IP:1.60.0.230X-Local=1} 1.60.0.230
{"ODBC":"Connection-StringIPX-For=233.60.255.120TransactionID:2} 233.60.255.120
{"ODBC":"Connection-StringIPX-For:1.1.1.90ID=1} 1.1.1.90

Here we are using the PATINDEX function https://learn.microsoft.com/en-us/sql/t-sql/functions/patindex-transact-sql?view=sql-server-ver16 to find the locations of patterns, and using SUBSTRING https://learn.microsoft.com/en-us/sql/t-sql/functions/substring-transact-sql?view=sql-server-ver16 to create a substring using those pattern locations.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading