Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function in SQL Server

Please help me, how to filter words in SQL using a function?

I'm having a hard time if I explain it so I'm giving example:

ID       |       WebsiteName      | ----------------------------------- 1        |      www.yahoo.com     | 2        |      www.google.com    | 3        |      www.youtube.com   | 

What I want is, how to get the name of the website. I want to select the record with an output like this. How to remove the 'www.' and '.com' in the record.

ID      |      WebsiteName --------------------------     1       |        yahoo 

thanks for the help. :D

like image 355
megastrong001 Avatar asked Jan 27 '13 18:01

megastrong001


People also ask

Can we CREATE FUNCTION in SQL Server?

A function is created using the Create function SQL command. The following query creates a new user-defined function. Now see a newly created function in the database. Now get Employee table information with the created function Fun_EmployeeInformation() using a select statement.


1 Answers

How about this?

CREATE FUNCTION dbo.StripWWWandCom (@input VARCHAR(250)) RETURNS VARCHAR(250) AS BEGIN     DECLARE @Work VARCHAR(250)      SET @Work = @Input      SET @Work = REPLACE(@Work, 'www.', '')     SET @Work = REPLACE(@Work, '.com', '')      RETURN @work END 

and then use:

SELECT ID, dbo.StripWWWandCom (WebsiteName) FROM dbo.YourTable ..... 

Of course, this is severely limited in that it will only strip www. at the beginning and .com at the end - nothing else (so it won't work on other host machine names like smtp.yahoo.com and other internet domains such as .org, .edu, .de and etc.)

like image 170
marc_s Avatar answered Oct 04 '22 13:10

marc_s