Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL UDF to get last word in string

Posted on 2011-03-10
2
Medium Priority
?
958 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 2000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Integration Management Part 2
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

926 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