Solved

SQL UDF to get last word in string

Posted on 2011-03-10
2
942 Views
Last Modified: 2012-05-11
I got the code below off the internet but the syntax is off.. What is the best way to create a UDF that pulls the last word out of a string?
CREATE FUNCTION dbo.ufn.Utility_Last_Word(@myString VARCHAR(4000) )
 RETURNS VARCHAR(4000)
 
RETURN
WITH find_last_blank(pos) AS (
VALUES LENGTH(@myString)
UNION ALL
SELECT pos - 1
  FROM find_last_blank
 WHERE pos > 0
   AND SUBSTR(in_string, pos, 1) <> ' '
)
SELECT SUBSTR(in_string, MIN(pos) + 1)
  FROM find_last_blank
;

Open in new window

0
Comment
Question by:cheryl9063
2 Comments
 
LVL 12

Accepted Solution

by:
mcv22 earned 500 total points
ID: 35099291
CREATE FUNCTION dbo.ufn_Utility_Last_Word(@myString VARCHAR(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
RETURN
	RIGHT
	(
		@myString, 
		CASE CHARINDEX(' ', REVERSE(@myString))
			WHEN 0 THEN LEN(@myString)
			ELSE CHARINDEX(' ', REVERSE(@myString)) - 1
		END
	)
END;

Open in new window

0
 
LVL 1

Author Closing Comment

by:cheryl9063
ID: 35099312
Thanks!
0

Featured Post

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Select question from MySQL 1 20
sql 2016 data tools breakdown.. 1 25
sql query display the latest row 10 51
Display field if column exists 7 31
PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question