Skip to content
Advertisement

SQL to get whole words till end from the keyword

Consider I have text from the field (notes) as below:

Please check http://example.com

I want a SQL query which fetches the link part only. That is to find keyword http and print till the last.

Output:

http://example.com

Also if the text field doesnt have any link, can we print NA?

CASE WHEN sys like '%Clo%'
THEN RIGHT( i.notes,LEN(i.notes) - CHARINDEX('http',i.notes,1)+1) 
ELSE "No Link Available" END  AS Cl_Link

Advertisement

Answer

For SQL Server you can consider this below logic-

DECLARE @T VARCHAR(MAX) = 'Please check http://example.com'
SELECT RIGHT(@T,LEN(@T) - CHARINDEX('http:',@T,1)+1)

For MySQL-

SET @T = 'Please check http://example.com';  
SELECT RIGHT(@T,LENGTH(@T) - POSITION("http:" IN @T)+1)

In case of select query using table, queries will be-

-- SQL Server
SELECT RIGHT(column_name,LEN(column_name) - CHARINDEX('http:',column_name,1)+1) FROM your_table_name

-- MySQL
SELECT RIGHT(column_name,LENGTH(column_name) - POSITION("http:" IN column_name)+1) FROM your_table_name

To apply ‘NA’ when no link available, please use the below logic-

DECLARE @T VARCHAR(MAX) = 'Please check http://example.com'
SELECT 
CASE 
    WHEN CHARINDEX('http:',@T,1) >= 1 THEN RIGHT(@T,LEN(@T) - CHARINDEX('http:',@T,1)+1)
    ELSE 'NA'
END
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement