SQL Server Extract name from a string [closed]

de90aj5v  于 2023-02-18  发布在  其他
关注(0)|答案(2)|浏览(138)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 20 hours ago.
Improve this question

Example:
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L

I want to extract only RadioNode

SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W

I want to extract only GALRNC1.

pokxtpni

pokxtpni1#

You can do it using SUBSTRING and LEFT and charindex

select LEFT(sub1, CHARINDEX(',MeContext', sub1) - 1)
from (
  select
  SUBSTRING(column1, charindex('SubNetwork=', column1, 2) + LEN('SubNetwork='), 20) sub1
  from mytable
) as s

charindex to get the position of your word in this case it is SubNetwork= .

SUBSTRING to Extract characters from a string.

LEFT to Extract characters from a string (starting from left).

Demo here

oaxa6hgo

oaxa6hgo2#

Please try the following solution.

It is using JSON and will work starting from SQL Server 2016 onwards.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, tokens NVARCHAR(1024));
INSERT @tbl (tokens) VALUES
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L'),
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W');
-- DDL and sample data population, end

SELECT t.* 
   , SubNetwork = JSON_VALUE(j,'$.SubNetwork') 
FROM @tbl AS t
CROSS APPLY (SELECT '{"' + REPLACE(REPLACE(STRING_ESCAPE('~'+tokens,'json')
   ,',','","')
   ,'=','":"') + '"}'
) AS t1(j);;

Output

idtokensSubNetwork
1SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917LRadioNode
2SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045WGALRNC1

相关问题