Replace everything after second occurrence with blank - sql

I have a string a/b/c I want to replace everything after second occurrence of "/" to blank so my result should like this a/b
any help will be appreciated.
Here what i tired nothing is working
select reverse(left(reverse('a/b/c'), charindex('/', reverse('a/b/c')) -1))
SELECT SUBSTRING('a/b/c', 1, LEN('a/b/c') )
SELECT STUFF('a/b/c', charindex('/', 'a/b/c'), 2, '');
select CHARINDEX('/','a/b/c')
select right ('a/b/c', CHARINDEX('/','a/b/c')-1)

You can use:
SELECT LEFT('a/b/c',CHARINDEX('/','a/b/c',CHARINDEX('/','a/b/c')+1)-1)
The optional third parameter of CHARINDEX is the starting position, ie where in the string it should start looking for the desired character, by nesting another CHARINDEX function as the third parameter you can find the 2nd occurrence. The +1 is so it doesn't find the same '/' in the nested CHARINDEX, the -1 is so it doesn't return the 2nd '/' as part of your result.

You can use the following:
select stuff('ashish jain',charindex('a','ashish jain',charindex('a','ashish jain')+1),1,'c')
It will replace 'a' with 'c' and return 'ashish jcin'.

Replace rest of all occurrence characters except first occurrence.
declare #word varchar(500)='B-123, Address1-Address2-Address3'
select CONCAT_WS('',left(#word,CHARINDEX('-',#word)), replace( substring(#word,CHARINDEX('-',#word)+1, len(#word)),'-',' '))

Related

Trim string after first occurrence of a character

I'm working with a varchar column in AWS Redshift. Each string in it has at least one hyphen (-).
I want to keep the substring after the first hyphen. For example:
00-11-22-33 -> 11-22-33
00-112233 -> 112233
The solutions to this question do not work when there are multiple hyphens in a string.
For instance:
select
split_part('00-11-22-33', '-', 2) as attempt1 -- returns '11'
, regexp_replace( '00-11-22-33', '.*-', '') as attempt2 -- returns '33'
;
I'm looking for a solution that returns 11-22-33.
If there's always a hyphen, and you always want only what is after the first hyphen, you may be working too hard.
Here's a more brute force approach.
select substring(
'00-11-22-33'
FROM charindex('-', '00-11-22-33') + 1)
)
or
select substring(
'00-11-22-33',
charindex('-', '00-11-22-33') + 1,
len('00-11-22-33') - charindex('-', '00-11-22-33')
)
or
select substring(
'00-11-22-33',
charindex('-', '00-11-22-33') + 1,
len('00-11-22-33')
)
...because it won't return more characters than exist.
You could match until the first hyphen with ^[^-]*-
And replace with an empty string.
regexp_replace('00-11-22-33', '^[^-]*-', '');
If there should be at least a single char after the hyphen, then you can match with this pattern and replace with capture group 1 like '$1' instead of an empty string.
^[^-]*-(.+)
If the char after the hyphen should not be another hyphen, then you can match a single char other than a hyphen and also replace with '$1'
^[^-]*-([^-].*)

how to replace dots from 2nd occurrence

I have column with software versions. I was trying to remove dot from 2nd occurrence in column, like
select REGEXP_REPLACE('12.5.7.8', '.','');
expected out is 12.578
sample data is here
Is it possible to remove dot from 2nd occurrence
One option is to break this into two pieces:
Get the first number.
Get the rest of the numbers as an array.
Then convert the array to a string with no separator and combine with the first:
select (split_part('12.5.7.8', '.', 1) || '.' ||
array_to_string((REGEXP_SPLIT_TO_ARRAY('12.5.7.8', '[.]'))[2:], '')
)
Another option is to replace the first '.' with something else, then get rid of the '.'s and replace the something else with a '|':
select translate(regexp_replace(version, '^([^.]+)[.](.*)$', '\1|\2'), '|.', '.')
from software_version;
Here is a db<>fiddle with the three versions, including the version a_horse_with_no_name mentions in the comment.
I'd just take the left and right:
concat(
left(str, position('.' in str)),
replace(right(str, -position('.' in str)), '.', '')
)
For a str of 12.34.56.78, the left gives 12. and the right using a negative position gives 34.56.78 upon which the replace then removes the dots

How to use Charindex for one or the other character

I have a string with a bunch of numbers but it contains one letter somewhere in the center of the string. This letter can either be 'A' or 'B'. I am trying to find out the position of this letter with the Charindex() function. However it doesn't work when you have two search parameters:
select charindex('[A,B]','190118A3700000')
I tried it out with a range and wildcards but it did not work. So what I want are these two separate queries combined in one:
select charindex('A','190118A3700000')
select charindex('B','190118A3700000')
Does anybody have an idea how to do this?
Thank you!!!
Use patindex():
select patindex('%[A,B]%', '190118A3700000')
Or, if you want the first non-digit:
select patindex('%[^0-9]%', '190118A3700000')
Here is a db<>fiddle.
charindex() does not understand wildcards.
If charindex doesn't find that character, it returns 0 so all you need to do is
select col, charindex('A', col) + charindex('B', col) as position
from your_table;
Another alternative
select col, charindex('A', replace(col, 'B', 'A')) as position
from your_table;
DEMO

SQL: how to select a substring between special characters

My string looks something like this:
\\\abcde\fghijl\akjfljadf\\
\\xyz\123
I want to select everything between the 1st set and next set of slashes
Desired result:
abcde
xyz
EDITED: To clarify, the special character is always slashes - but the leading characters are not constant, sometimes there are 3 slashes and other times there are only 2 slashes, followed by texts, and then followed by 1 or more slashes, some more texts, 1 or more slash, so on and so forth. I'm not using any adapter at all, just looking for a way to select this substring in my SQL query
Please advise.
Thanks in advance.
You could do a cross join to find the second position of the backslash. And then, use substring function to get the string between 2nd and 3rd backslash of the text like this:
SELECT substring(string, 3, (P2.Pos - 2)) AS new_string
FROM strings
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\')))
) AS P1(Pos)
CROSS APPLY (
SELECT (charindex('\', replace(string, '\\', '\'), P1.Pos + 1))
) AS P2(Pos)
SQL Fiddle Demo
UPDATE
In case, when you have unknown number of backslashes in your string, you could just do something like this:
DECLARE #string VARCHAR(255) = '\\\abcde\fghijl\akjfljadf\\'
SELECT left(ltrim(replace(#string, '\', ' ')),
charindex(' ',ltrim(replace(#string, '\', ' ')))-1) AS new_string
SQL Fiddle Demo2
Use substring, like this (only works for the specified pattern of two slashes, characters, then another slash):
declare #str varchar(100) = '\\abcde\cc\xxx'
select substring(#str, 3, charindex('\', #str, 3) - 3)
Replace #str with the column you actually want to search, of course.
The charindex returns the location of the first slash, starting from the 3rd character (i.e. skipping the first two slashes). Then the substring returns the part of your string starting from the 3rd character (again, skipping the first two slashes), and continuing until just before the next slash, as determined by charindex.
Edit: To make this work with different numbers of slashes at the beginning, use patindex with regex to find the first alphanumeric character, instead of hardcoding that it should be the third character. Example:
declare #str varchar(100) = '\\\1Abcde\cc\xxx'
select substring(#str, patindex('%[a-zA-Z0-9]%', #str), charindex('\', #str, patindex('%[a-zA-Z0-9]%', #str)) - patindex('%[a-zA-Z0-9]%', #str))
APH's solution works better if your string always follows the pattern as described. However this will get the text despite the pattern.
declare #str varchar(100) = '\\abcde\fghijl\akjfljadf\\'
declare #srch char(1) = '\'
select
SUBSTRING(#str,
(CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1),
CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1))
- (CHARINDEX(#srch,#str,(CHARINDEX(#srch,#str,1)+1))+1)
)
Sorry for the formatting.
Edited to correct user paste error. :)

T-SQL Substring - Last 3 Characters

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?
So the column text is IDS_ENUM_Change_262147_190 and I need 190
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT() in the same way.
Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
declare #newdata varchar(30)
set #newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(#newdata),0,charindex('_',reverse(#newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Reverse the text
Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
Reversed the reversed string to give you your desired substring
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'