简体   繁体   中英

extract text from the string

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.

select substring(firstpart,1,CHARINDEX('/',firstpart)-1)
from 
(select 
substring(pattern,
                 CHARINDEX('/',pattern)+1,
                 datalength(pattern))  as firstpart
from tessst
)X;

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.

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