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)
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.
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.
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.
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
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With