I want to write a sql statement to trim a string 'Hello' from the string "Hello World'. Please suggest.
SQL Server TRIM() FunctionThe TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.
The LTRIM function is used to remove the leading spaces from a string of characters or character expressions. L is for left and TRIM means to remove unwanted leading spaces.
Remove first 5 characters with RIGHT function. RTRIM function truncate all trailing spaces. LEN function returns the length of the string.
To remove the left-most word, you'll need to use either RIGHT or SUBSTRING. Assuming you know how many characters are involved, that would look either of the following:
SELECT RIGHT('Hello World', 5)
SELECT SUBSTRING('Hello World', 6, 100)
If you don't know how many characters that first word has, you'll need to find out using CHARINDEX, then substitute that value back into SUBSTRING:
SELECT SUBSTRING('Hello World', CHARINDEX(' ', 'Hello World') + 1, 100)
This finds the position of the first space, then takes the remaining characters to the right.
select substring( field, 1, 5 ) from sometable
For 'Hello' at the start of the string:
SELECT STUFF('Hello World', 1, 6, '')
This will work for 'Hello' anywhere in the string:
SELECT REPLACE('Hello World', 'Hello ', '')
You can use LEN in combination with SUBSTRING:
SELECT SUBSTRING(myColumn, 7, LEN(myColumn)) from myTable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With