实际上有两种方法可以解决这个问题。
从右边寻找相同的东西。
或者从左边寻找差异。
示例 sn-p:
declare @bookyear varchar(9);
set @bookyear = '1993-1997';
--
-- looking for different digits from left to right
--
set @bookyear = left(@bookyear,5) +
case
when left(@bookyear,1) != substring(@bookyear,6,1) then right(@bookyear,4)
when left(@bookyear,2) != substring(@bookyear,6,2) then right(@bookyear,3)
when left(@bookyear,3) != substring(@bookyear,6,3) then right(@bookyear,2)
else right(@bookyear,1)
end;
select @bookyear as bookyear1;
-- reset variable
set @bookyear = '1993-1997';
--
-- looking for same digits from right to left
--
set @bookyear = left(@bookyear,5) +
case
when left(@bookyear,3) = substring(@bookyear,6,3) then substring(@bookyear,9,1)
when left(@bookyear,2) = substring(@bookyear,6,2) then substring(@bookyear,8,2)
when left(@bookyear,1) = substring(@bookyear,6,1) then substring(@bookyear,7,3)
else substring(@bookyear,6,4)
end;
select @bookyear as bookyear2;
使用表变量的测试 sn-p:
declare @Test table (bookyear varchar(9));
insert into @Test (bookyear) values
('1993-1997'),
('1923-1935'),
('1998-2015'),
('2095-2115');
select
bookyear,
left(bookyear,5) +
case
when left(bookyear,1) != substring(bookyear,6,1) then right(bookyear,4)
when left(bookyear,2) != substring(bookyear,6,2) then right(bookyear,3)
when left(bookyear,3) != substring(bookyear,6,3) then right(bookyear,2)
else right(bookyear,1)
end as bookyear1,
left(bookyear,5) +
case
when left(bookyear,3) = substring(bookyear,6,3) then substring(bookyear,9,1)
when left(bookyear,2) = substring(bookyear,6,2) then substring(bookyear,8,2)
when left(bookyear,1) = substring(bookyear,6,1) then substring(bookyear,7,3)
else substring(bookyear,6,4)
end as bookyear2
from @Test;
返回:
bookyear bookyear1 bookyear2
1993-1997 1993-7 1993-7
1923-1935 1923-35 1923-35
1998-2015 1998-2015 1998-2015
2095-2115 2095-115 2095-115
对 rextester 的测试here