Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server query to remove the last word from a string

Tags:

sql

sql-server

There's already an answer for this question in SO with a MySQL tag. So I just decided to make your lives easier and put the answer below for SQL Server users. Always happy to see different answers perhaps with a better performance.

Happy coding!

like image 766
Baz Guvenkaya Avatar asked Jan 21 '16 01:01

Baz Guvenkaya


People also ask

How do I remove a word from a string in SQL?

We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.

How do I remove the last character of a line in SQL?

Remove and Replace Carriage Returns and Line Breaks in SQL Using SQL to remove a line feed or carriage return means using the CHAR function. A line feed is CHAR(10); a carriage return is CHAR(13).


2 Answers

SELECT SUBSTRING(@YourString, 1, LEN(@YourString) - CHARINDEX(' ', REVERSE(@YourString)))

Edit: Make sure @YourString is trimmed first as Alex M has pointed out:

SET @YourString = LTRIM(RTRIM(@YourString))
like image 166
Baz Guvenkaya Avatar answered Oct 13 '22 19:10

Baz Guvenkaya


DECLARE @Sentence    VARCHAR(MAX) = 'Hi This is Pavan Kumar'

SELECT SUBSTRING(@Sentence, 1, CHARINDEX(' ', @Sentence) - 1) AS [First Word],
       REVERSE(SUBSTRING(REVERSE(@Sentence), 1, 
               CHARINDEX(' ', REVERSE(@Sentence)) - 1)) AS [Last Word]

enter image description here

like image 44
pavan kumar Avatar answered Oct 13 '22 17:10

pavan kumar