Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex T-SQL Substring

Just to be clear, I cannot use CLR UDF for this and SUBSTRING and CHARINDEX just don't cut the mustard.

We have a faux account management system with accounts being sub-accounts of others, better described here (with tables too :) )

Now, assuming I have an account 2.4.1.3 (obviously, the parent becomes 2.4.1) and if wanted to extract the 'prefix' 2.4.1 so that I may create another sibling account with the next ID in line (assume 2.4.1.4) how would I go about splitting such a string in T-SQL?

Of course, a similar way can be applied to children accounts, but that's just butterscotch for this sundae.

like image 786
Mustafa Ismail Mustafa Avatar asked Feb 12 '26 19:02

Mustafa Ismail Mustafa


1 Answers

Try something like this:

DECLARE @accountno VARCHAR(50) = '2.4.1.3'

SELECT 
   REVERSE(@accountno),
   CHARINDEX('.', REVERSE(@accountno)),
   SUBSTRING(@accountno, 1, LEN(@accountno) - CHARINDEX('.', REVERSE(@accountno)))

That third element in the SELECT statement should be the one that extracts the "prefix" 2.4.1 from your account number string.

Basically, what I do is reverse the string and then look for the first occurence of the dot ('.') - the first in the reversed string is the last in the original string, and that's what you want to extract up to.

like image 154
marc_s Avatar answered Feb 15 '26 19:02

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!