Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract last two words from my string

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

like image 328
Pரதீப் Avatar asked Sep 28 '16 10:09

Pரதீப்


People also ask

How do I extract part of a text string?

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).

How do I extract text from two words in Excel?

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.


2 Answers

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
like image 190
gofr1 Avatar answered Oct 18 '22 10:10

gofr1


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 _

like image 44
NEER Avatar answered Oct 18 '22 10:10

NEER