Customize domainname from SQL URL

I have a dataset:

www.google.com.sg
www.yahoo.com
marketwatch
bing.com
bbc.co.uk

Some data have www., some do not. Some have .com/ .com.sg/ .com.uland some do not.

How to extract only a name, for example. google, yahoo, marketwatch, bing, bbcUsing SQL?

+2
source share
3 answers

Using MS SQL Server syntax for CHARINDEX and SUBSTRING, you can do something like ...

(Intentionally overly split to make the step obvious.)

WITH
  url_start AS
(
  SELECT
    *,
    CASE WHEN LEFT(myURL, 4) = 'www.' THEN 4 ELSE 1 END AS d_start
  FROM
    myTable
)
,
  url_end
AS
(
  SELECT
    *,
    CASE WHEN
      CHARINDEX('.', myURL, d_start) = 0
    THEN
      LEN(myURL) + 1
    ELSE
      CHARINDEX('.', myURL, d_start)
    END as d_end
  FROM
    url_start
)
SELECT
  *,
  SUBSTRING(myURL, d_start, d_end - d_start) AS domain
FROM
  url_end
+2
source

Replace SQL, www., , , .

Select Replace(URLColumn, 'www.','') as [CleanURLColumn]
From YourTable

, - , , :

Select  Case
        When CharIndex('.', Replace(URL, 'www.','')) > 0 then
           Left(Replace(URL, 'www.',''), CharIndex('.',Replace(URL, 'www.',''))-1)
        Else
           Replace(URL, 'www.','')
        End as [CleanURL]

From dbo.YourTable
+1
;with cte as
(
  select replace(URL, 'www.', '')+'.' as url
  from myTable
)
select
  left(url, charindex('.', url)-1)
from cte
0
source

All Articles