I have a field in a table that has both leading and trailing characters that I would like to remove.
This Statement
SELECT FullName AS Category FROM dbo.inventory
produces this result in a table (partial result shown):
I would like to remove the before the dash which would remove "Parts - " and everything trailing the colon ':' so I can be left with only the category and get a table like this:
I have tried this and successfully removed the preceding "Parts -" but successfully combine the statement with removing everything after the colon ":"
SELECT LTRIM(RTRIM(REPLACE(FullName, 'Parts -', ''))) AS Category FROM dbo.inventory
Produces this result:
Thanks for you help!
A method using LEFT & CHARINDEX:
SELECT REPLACE(LEFT(FullName, CHARINDEX(':', FullName) - 1), 'Parts - ', '')
CHARINDEX finds the index number of the colon character in the full string, -1 is included to remove it too. LEFT then truncates the string to that position. The REPLACE functions as it does in your original example, removing the 'Parts - ' portion (note I've included the space following the hyphen).
LTRIM and RTRIM only remove leading/trailing spaces respectively, so they won't be useful here.
Code to handle rows containing no colon (will return a blank string):
SELECT REPLACE(REPLACE(LEFT(Fullname, CHARINDEX(':', Fullname)), 'Parts - ', ''), ':', '')