March 21, 2016 at 3:30 am
Hi,
I have strings like
WebApp - 10148
Smart - App - 1458
Expected Result
WebApp
Smart - App
I want to trim the characters from - to numbers from right.
I have tried the below query and the result is this
WebApp
Smart
select LEFT(app+' - ', CHARINDEX(' - ',app+' - ')-1) from repository
Can anyone assist me sort this?
March 21, 2016 at 3:34 am
Use REVERSE, LEFT and LEN to find the position of the final hyphen, then use LEFT to return all the characters up to that point.
John
March 21, 2016 at 4:06 am
Can you provide an example, since I am new to sql.
March 21, 2016 at 4:06 am
Can you provide an example? Since I am new to sql.
March 21, 2016 at 4:17 am
Then this is a good learning opportunity for you. You've already shown you can use LEFT and CHARINDEX. Read about LEN and REVERSE and what they do, and see if you can build an expression that will return what you're looking for. Post back if you run into any difficulty and we'll try to help.
John
March 21, 2016 at 5:51 am
got it!
reverse(right(reverse(app), len(app) - charindex('-',reverse(app),1)))
March 21, 2016 at 10:33 am
vigneshlagoons 51204 (3/21/2016)
got it!reverse(right(reverse(app), len(app) - charindex('-',reverse(app),1)))
That uses 3 reverses and that's expensive. I'll try to get back to this tonight.
Personally, I wouldn't use any reverses for this.
--Jeff Moden
Change is inevitable... Change for the better is not.
March 21, 2016 at 3:36 pm
select LEFT(@var, len(@var)- CHARINDEX('-',REVERSE(@var), 0))
March 21, 2016 at 5:42 pm
-- Sample values in a table
DECLARE @repository TABLE(someid int, string varchar(100));
INSERT @repository VALUES (1,'WebApp - 10148'),(2,'Smart - App - 1458'),(3,'No Number - here');
-- Solution if there's always a number
SELECT String, NewString = SUBSTRING(string, 1, PATINDEX('% - [0-9]%', string)-1)
FROM @repository
WHERE someid <> 3;
-- Solution for when there isn't always a number
SELECT
String,
NewString = ISNULL(SUBSTRING(string,1,NULLIF(PATINDEX('% - [0-9]%',string),0)-1),string)
FROM @repository;
-- Itzik Ben-Gan 2001
Viewing 9 posts - 1 through 8 (of 8 total)
You must be logged in to reply to this topic. Login to reply