-4

how to get code and sub code from query sql like this from column A with

format :

[very long name | code | subcode] 

for the example

[Pear | S01 | 10]
[Pineapple | S01 | 9]

PS : there is no square brackets but the the pipe delimiters is real

Yan Susanto
  • 353
  • 4
  • 22

2 Answers2

3

Try this; DEMO - UPDATED WITH A TABLE

--declare @s varchar(50)='[Pineapple | S01 | 9]'

select substring(yourColumn,ind1 + 1,ind2-(ind1 +1)) code, 
       substring(yourColumn,ind2 + 1,len(yourColumn)-(ind2 + 1)) subcode
FROM ( 
  SELECT yourColumn, charindex('|',yourColumn,1) ind1, 
         charindex('|',yourColumn,charindex('|',yourColumn,1)+1) ind2 
  FROM yourTable
) X
Kaf
  • 33,101
  • 7
  • 58
  • 78
1

Assuming your codes are always three letters, you could use some built-in functions to help you out:

WITH Data(Sample) AS
(
    SELECT 'Pear | S01 | 10' UNION
    SELECT 'Pineapple | S01 | 9'
)
SELECT
    SUBSTRING([Sample], CHARINDEX(' | ', [Sample], 1) + 3, 3) AS Code,
    REVERSE(SUBSTRING(REVERSE([Sample]), 1, 
        CHARINDEX(' | ', REVERSE([Sample]), 1) - 1)) AS SubCode
FROM
    data
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194