2

I need to extract text from the string KWR/50X50X5/1.4301 between /, or 50x50x5 in T-SQL. I've tried using Substing, however, does not go to me. Ultimately, I need to add the values (sum values) ​​in between / without character x (for example, 50 + 50 + 5 = 105) I would be grateful for your help.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
AdiT
  • 51
  • 1
  • 8

2 Answers2

0
select substring(firstpart,1,CHARINDEX('/',firstpart)-1)
from 
(select 
substring(pattern,
                 CHARINDEX('/',pattern)+1,
                 datalength(pattern))  as firstpart
from tessst
)X;
anwaar_hell
  • 756
  • 5
  • 23
0

Try this:

DECLARE @t TABLE (id INT,  v VARCHAR(100) )

INSERT  INTO @t
VALUES  ( 1, 'PWPQ/80X20/1.4301' ) ,
        ( 2, 'PWO/120/1.4404' ),
        ( 3, 'PWOI/120X9X90X80/1.4404' )


;WITH cte1 AS(SELECT id, SUBSTRING(v, 
                                   CHARINDEX('/', v) + 1, 
                                   CHARINDEX('/', v, CHARINDEX('/', v) + 1) - CHARINDEX('/', v) - 1) AS v
             FROM @t),
      cte2 AS(SELECT id, CAST ('<X>' + REPLACE(v, 'X', '</X><X>') + '</X>' AS XML) AS v FROM  cte1)
SELECT id, SUM(Split.a.value('.', 'int')) AS v  
FROM  cte2 a CROSS APPLY v.nodes ('/X') AS Split(a)
GROUP BY id

Output:

id  v
1   100
2   120
3   299

First cte is for extracting value between /. Second cte for casting those values to xml format. The last statement is standard trick for transposing string with delimeter to separate rows.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
  • great, did not mention that I have a table in which the specified text (code ) . I would like to do a select from table and point the id of the record and the query will return me the value of that figured out . Sory for the confusion – AdiT Oct 29 '15 at 09:30