简体   繁体   中英

SQL Server 2008 R2: Update table using pattern

I have the following table with some records:

Table : Test_One

create table Test_One
(
  Cola varchar(50)
);

Inserting records:

Insert into Test_One values('1_123456');
Insert into Test_One values('123456898_121');
Insert into Test_One values('12345633_789');
Insert into Test_One values('986_12345622');
Insert into Test_One values('3457_123456221');
Insert into Test_One values('2_123456456');
Insert into Test_One values('1234567878_5674');
Insert into Test_One values('23_1234560976');
Insert into Test_One values('6_12345634234');
...
...
Millions

Now I want to update the column Cola . I want to remove the part of string from starting and also from end. The starting string which is end with _ like 1_,2_,23_,6_,3457_,986_ want to remove and the end string which is starting with _ like _121,_789,_5674 want ot remove.

Result should be:

Cola
-----------
123456
123456898
12345633
12345622
123456221
123456456
1234567878
1234560976
12345634234
...
...

Using CHARINDEX and SUBSTRING :

SELECT
    *,
    CASE
        WHEN LEN(SUBSTRING(Cola, CHARINDEX('_', Cola) + 1, LEN(Cola) - CHARINDEX('_', Cola))) >=
                LEN(SUBSTRING(Cola, 0, CHARINDEX('_', Cola)))
            THEN SUBSTRING(Cola, CHARINDEX('_', Cola) + 1, LEN(Cola) - CHARINDEX('_', Cola))
        ELSE
            SUBSTRING(Cola, 0, CHARINDEX('_', Cola))
    END AS UpdatedCola  
FROM Test_One

Using CHARINDEX , left and right

select
    case
    when char_ind > cola_len/2 then
        left(cola, char_ind - 1)
    when char_ind < cola_len/2 then
        right(cola, cola_len - char_ind)
    else --char_ind = cola_len/2; take cola
        cola
    end as new_cola
from (
  select 
      cola, 
      CHARINDEX('_', cola) char_ind, 
      len(cola) cola_len 
  from test_one
) as x

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