You are using the wrong data types to begin with. There is such a thing as a DateTime datatype in SQL why don't you use that ?
An example of some code using it :
ALTER FUNCTION [dbo].[RekenTerug]
(
@EindDatum datetime,
@Periodes int
)
RETURNS datetime
AS
BEGIN
DECLARE @ResultVar datetime;
DECLARE @BeginDatum datetime;
DECLARE @VerlofPeriodes int;
-- zet de einddatum naar het begin van een periode
SELECT @EindDatum =
CASE
WHEN datepart(dw,@EindDatum) = 1 THEN @EindDatum -4 --zondag, zet op woensdag
WHEN datepart(dw,@EindDatum) = 2 THEN @EindDatum --maandag, maandag is ok
WHEN datepart(dw,@EindDatum) = 3 THEN @EindDatum -1 --dinsdag, zet op maandag
WHEN datepart(dw,@EindDatum) = 4 THEN @EindDatum --woensdag, woensdag is ok
WHEN datepart(dw,@EindDatum) = 5 THEN @EindDatum -1 --donderdag, woensdag is ok
WHEN datepart(dw,@EindDatum) = 6 THEN @EindDatum -2 --vrijdag, woensdag is ok
WHEN datepart(dw,@EindDatum) = 7 THEN @EindDatum -3 --zaterdag, woensdag is ok
END
--Als het aantal periodes dat je moet terugrekenen oneven is,
--zet dan de begindatum aan het begin van de vorige periode
if @Periodes % 2 = 1
begin
SELECT @Periodes = @Periodes - 1;
SELECT @BeginDatum =
CASE
WHEN datepart(dw,@EindDatum) = 4 THEN @EindDatum - 2
WHEN datepart(dw,@EindDatum) = 2 THEN @EindDatum - 5
END
end
else SELECT @BeginDatum = @EindDatum
--reken terug
SELECT @BeginDatum = @BeginDatum - @Periodes/2*7
--tel het aantal verlofperiodes dat in het interval [BeginDatum,EindDatum]
SELECT @VerlofPeriodes = COUNT(*) FROM VerlofRegeling2
WHERE (BeginDatum BETWEEN @BeginDatum and @EindDatum-1) and
(EindDatum BETWEEN @BeginDatum and @EindDatum-1)
SELECT @ResultVar =
CASE
WHEN @VerlofPeriodes = 0 THEN @BeginDatum
ELSE dbo.RekenTerug(@BeginDatum,@VerlofPeriodes)
END
RETURN @ResultVar
END
I've indicated in bold where some date artithmatic is used.