Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the second occurrence from charindex function in sql server

Tags:

sql

sql-server

I need to get the second occurrence of the space for below text. It should be the space after the 56, but I'm getting 15th position before the 56 as the first one.

select charindex(' ', 'Posted/edited: 56 days ago', 2)
like image 534
Haz Avatar asked Apr 10 '19 11:04

Haz


People also ask

How do I find the second occurrence of a character in SQL Server?

For example, to find the second occurrence of 'B' in the source string 'ABCABC', we could use SELECT LOCATE('B', 'ABCABC', LOCATE('B', 'ABCABC') + 1) + LOCATE('B', 'ABCABC') FROM SYSIBM/SYSDUMMY1 that will return 5. In this case, we used the “second” locate in the list to find the first “B” in the string, which was 2.

How do you find nth occurrence of a character in a string in SQL Server?

T-SQL's CHARINDEX() function is a useful for parsing out characters within a string. However, it only returns the first occurrence of a character. Oftentimes one needs to locate the Nth instance of a character or a space, which can be a complicated task in standard T-SQL.

How do I get the last Charindex in SQL?

If you want to get the index of the last space in a string of words, you can use this expression RIGHT(name, (CHARINDEX(' ',REVERSE(name),0)) to return the last word in the string.


Video Answer


2 Answers

You need to set START_LOCATION for CHARINDEX. It means after what character charindex should be found. In our example, we need to find after 56. So the code should looks like this:

select CHARINDEX(' ', 'Posted/edited: 56 days ago', 
    CHARINDEX('56', 'Posted/edited: 56 days ago', 0));

OUTPUT:

18
like image 78
StepUp Avatar answered Oct 03 '22 12:10

StepUp


You are already getting position of the second space (' ') in your query => 15. To clarify for example, you can use it to extract content from that point onwards, using following

select substring('Posted/edited: 56 days ago', 
           charindex(' ', 'Posted/edited: 56 days ago', 2) + 1, 
           len('Posted/edited: 56 days ago'))
like image 41
Gro Avatar answered Oct 03 '22 10:10

Gro