Reputation: 155
If someone can help me with selecting only left part of string before '('.
For example I have this string:
SS0054(BOSCH)
and I want to select only text to the LEFT of the (
, and ignore the right part.
I have managed to select left part, but in my data I also have string values without (
in it for example just SS0054
, but then I get error:
Invalid length parameter passed to the left function
How can I select all values, to the left of (
in strings where a (
exists?
Here is my code:
SELECT UPPER(LEFT(RTRIM(LTRIM('SS0054(BOSCH)')), CHARINDEX('(', REVERSE(RTRIM(LTRIM('SS0054(BOSCH)')))) - 1));
Thanks in advance
Upvotes: 1
Views: 1314
Reputation: 5042
Just check '(' in your string like this:
DECLARE @string NVARCHAR(50)='78BD0920-2(VALEO)'
SELECT CASE WHEN CHARINDEX('(',@string)!=0
THEN
UPPER(LEFT(RTRIM(LTRIM(@string)), CHARINDEX('(', @string) - 1))
ELSE @string -- ( not exist
end
Upvotes: 3
Reputation: 2432
Use a CASE statement, and you can simplify your original code to find the text before the '('.
SELECT
CASE
WHEN CHARINDEX('(', MY_STR) <> 0 THEN
UPPER(SUBSTRING(MY_STR, 0, CHARINDEX('(', MY_STR)))
ELSE
UPPER(MY_STR) -- or whatever else you wish to display
END
Upvotes: 2
Reputation: 9
It seems to me that you always want the first 6 characters. Will substring work?
SELECT SUBSTRING('SS0054(BOSCH)', 0,7) AS partString;
You can add the LTRIM, RTRIM if you require
SELECT SUBSTRING(RTRIM(LTRIM(' SS0054(BOSCH) ' )), 0,7) AS partString;
Upvotes: -1