假设有一个字符串 M004US8060UfG 如果前四个字符 M004 ,那么我必须删除 M004 并保留US8060UfG 如果最后一个字符为零,即 M004US8060Uf0 ,则删除最后一个零,仅保留 US8060Uf
答案 0 :(得分:0)
尝试这样
DECLARE @t TABLE(s VARCHAR(100))
INSERT INTO @t VALUES('M004US8060UfG'),('M004US8060Uf0'),('SomeOther')
SELECT Step2
FROM @t AS t
CROSS APPLY(SELECT CASE WHEN LEFT(t.s,4)='M004' THEN SUBSTRING(t.s,5,9999) ELSE t.s END AS Step1 ) AS A
CROSS APPLY(SELECT CASE WHEN RIGHT(Step1,1)='0' THEN LEFT(Step1,LEN(Step1)-1) ELSE Step1 END AS Step2) AS B
结果
US8060UfG
US8060Uf
SomeOther
答案 1 :(得分:0)
也许一个简单的案例(偷走Shnugo的桌子)
注意:这假定只删除一个尾随零
DECLARE @t TABLE(s VARCHAR(100))
INSERT INTO @t VALUES('M004US8060UfG'),('M004US8060Uf0'),('SomeOther'),('Trailing0')
Select *
,NewValue = case when S like 'M004%0' then substring(S,5,len(S)-5)
when S like 'M004%' then substring(S,5,len(S))
when S like '%0' then substring(S,1,len(S)-1)
else S end
From @t
<强>返回强>
s NewValue
-------------- -----------
M004US8060UfG US8060UfG
M004US8060Uf0 US8060Uf
SomeOther SomeOther
Trailing0 Trailing