Hi,
This solution is similar like other posts. this one is not very efficient but it's enough to solve the problem.
--goal: Output CombYr = 3/4/5
--Input: BegYr int, EndYr int
--assume inputs are valid. and year is 4-digit format. and EndYr - BegYr <= 10
DECLARE @BegYr INT = 2010, @EndYr INT = 2020;
DECLARE @YrDiff SMALLINT, @CurrentYr SMALLINT, @CombYr VARCHAR(250)= '';
SET @YrDiff = @EndYr - @BegYr; --difference btw start and end year
SET @CurrentYr = CAST(SUBSTRING(CAST(@BegYr AS CHAR(4)),4,1) AS SMALLINT); --last digit of current year
WHILE @YrDiff >= 0
BEGIN
IF @YrDiff = 0
SET @CombYr = @CombYr + CAST(@CurrentYr AS VARCHAR(3));
ELSE
SET @CombYr = @CombYr + CAST(@CurrentYr AS VARCHAR(3))+ '/';
SET @YrDiff = @YrDiff - 1;
SET @CurrentYr = @CurrentYr + 1;
END
SELECT @CombYr AS CombinedYearOuput; --output result
--------------------------------------------------------------------------------------
Hai Ton
My Db4Breakfast blog.