我有下表和一些记录:
表:Test_One
create table Test_One
(
Cola varchar(50)
);
插入记录:
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
现在我想更新Cola列.我想从开始和删除字符串的一部分
从结束.以__,2_,23_,6_,3457_,986_结尾的起始字符串想要删除和
以_开头的结束字符串如_121,_789,_5674想要删除.
结果应该是:
Cola
-----------
123456
123456898
12345633
12345622
123456221
123456456
1234567878
1234560976
12345634234
...
...
最佳答案 使用CHARINDEX和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