I trying extract last words from my string.
Example
Input String : GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD
Result
╔═══════════╦════════════╗
║ FIRST_COL ║ SECOND_COL ║
╠═══════════╬════════════╣
║ CCC ║ DDDDD ║
╚═══════════╩════════════╝
I have the below code working.
DECLARE @STR VARCHAR(50) = 'GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD'
SELECT
Reverse(LEFT(Stuff(Reverse(@STR), 1, Charindex('_', Reverse(@STR)) + 1 - 1, ''), Charindex('_', Stuff(Reverse(@STR), 1, Charindex('_', Reverse(@STR)) + 1 - 1, '')) - 1)) as FIRST_COL,
Reverse(LEFT(Reverse(@STR), Charindex('_', Reverse(@STR)) - 1)) as SECOND_COL
Is there any simpler to achieve this
To extract a substring from the middle of a text string, you need to identify the position of the marker right before and after the substring. For example, in the example below, to get the domain name without the .com part, the marker would be @ (which is right before the domain name) and . (which is right after it).
The easiest way to extract a substring between two delimiters is to use the text to column feature in Excel, especially if you have multiple delimiters. In this example, use =MID(A2, SEARCH(“-“,A2) + 1, SEARCH(“-“,A2,SEARCH(“-“,A2)+1) – SEARCH(“-“,A2) – 1) in cell B2 and drag it to the entire data range.
You can use XML:
DECLARE @input nvarchar(max) = 'GGG_FFFF_AAAA_BBBBBB_CCC_DDDDD',
@x xml
SELECT @x = CAST('<a>'+REPLACE(REVERSE(@input),'_','</a><a>')+'</a>' as xml)
SELECT REVERSE(@x.value('/a[2]','nvarchar(max)')) as FIRST_COL,
REVERSE(@x.value('/a[1]','nvarchar(max)')) as SECOND_COL
Output:
FIRST_COL SECOND_COL
CCC DDDDD
You can use PARSENAME
(starting with 2012)
DECLARE @Val NVARCHAR(100)= 'AAAA_BBB_CCC_DDDDD'
SELECT PARSENAME(REPLACE(@Val, '_', '.'), 1) -- DDDDD
SELECT PARSENAME(REPLACE(@Val, '_', '.'), 2) -- CCC
Note: This is not correct for more than 3 _
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