简体   繁体   中英

select string between 3rd and 4th pipe delimiter

I have a column that contains values such as

Column
Asset|Class1|Category1|Group1|Account1
Expense|Class23|Category23|Group23|Account23

I want to select the string between 3rd and 4th occurrence of my pipe delimiter, how can I achieve this?

I've tried the PARSENAME and charindex+stuff function, but they have limitations, like max 128 characters. Also our SQL server has limited regex support. Any ideas?

SELECT REVERSE(PARSENAME(REVERSE(replace(LTRIM(Column), '|', '.')), 3))

My select need to return: Group1 Group23

Perhaps this will help

Example

Declare @YourTable table (ID int,[Column] varchar(max))
Insert Into @YourTable values
 (1,'Asset|Class1|Category1|Group1|Account1')
,(2,'Expense|Class23|Category23|Group23|Account23')

Select ID
      ,SomeValue = convert(xml,'<x>' + replace([Column],'|','</x><x>')+'</x>').value('/x[3]','varchar(100)')
 From @YourTable

Returns

ID  SomeValue
1   Category1
2   Category23

You can also use STRING_SPLIT() if you have 2016+

CREATE TABLE T(
  ID INT IDENTITY(1,1),
  Str VARCHAR(45)
);

INSERT INTO T(Str) VALUES 
('Asset|Class1|Category1|Group1|Account1'),
('Expense|Class23|Category23|Group23|Account23');

SELECT V Str
FROM (
       SELECT Value V,
              ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) RN
       FROM T CROSS APPLY STRING_SPLIT(Str, '|')
     ) TT
WHERE RN = 3;

Returns:

Str
---------
Category1
Category23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM