简体   繁体   中英

How to extract this specific data from a particular column in SQL Server?

I have column with below data:

Change 
18        MCO-005329
A        ECO-12239
0        ECO-25126
X1        ECO-05963
NA        MCO-003778
C        ECO-08399
MCO-003759
ECO-00643217
NULL

I want to extract the output like below:

   MCO-005329
   ECO-12239
   ECO-25126
   ECO-05963
   MCO-003778
   ECO-08399
   MCO-003759
   ECO-00643217

I have implemented the code like below:

  select DISTINCT change,
  case when change like 'MCO%' THEN change when change like 'ECO-%' THEN change 
  when change like '%MCO-%' then LTRIM(RTRIM(SUBSTRING(change,10,19) ))
  when change like '%ECO-%' then LTRIM(RTRIM(SUBSTRING(change,10,19) )) 
  else '' end x from table 

You could use CHARINDEX() and RIGHT() as

SELECT *, RIGHT(Change, CHARINDEX('-', REVERSE(Change)) + 3)
FROM
(
  VALUES
  ('18        MCO-005329'),
  ('A        ECO-12239'),
  ('0        ECO-25126'),
  ('X1        ECO-05963'),
  ('NA        MCO-003778'),
  ('C        ECO-08399'),
  ('MCO-003759'),
  ('ECO-00643217'), ('hhh kkk-k'),
  (NULL)
) T(Change) 

You can parse out the values from your requirements using SPLIT_STRING , outer apply , and a simple where clause without relying on hard coding any specific string length or position values, its dynamic.

SELECT D2.*
FROM
(
    select '18        MCO-005329'
    union select 'A        ECO-12239'
    union select '0        ECO-25126'
    union select 'X1        ECO-05963'
    union select 'NA        MCO-003778'
    union select 'C        ECO-08399'
    union select 'MCO-003759'
    union select 'ECO-00643217'
    union select NULL
) T(Change) 
outer apply
(
    select value
    from
    string_split(Change, ' ') d
) d2
where d2.value like '%-%' or d2.value is null

If you dont want nulls then smiply remove or d2.value is null

在此处输入图像描述

https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-ver15 https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver15

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