DROP FUNCTION IF EXISTS dd DELIMITER CREATE FUNCTION dd strtdate DATE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
DROP FUNCTION IF EXISTS dd;
DELIMITER //
CREATE FUNCTION dd ( strtdate DATE, fndate DATE )
RETURNS TEXT DETERMINISTIC
BEGIN
DECLARE ddays TEXT; /* Сюда возвращаем результат функции */
DECLARE startdate DATE DEFAULT strtdate; /* Начальная дата */
DECLARE findate DATE DEFAULT fndate; /* Конечная дата */
DECLARE counterdays INT; /* Счетчик дней до 1 числа след месяца */
/* Проверка на порядок дат */
IF findate < startdate THEN
SET startdate = fndate;
SET findate = strtdate;
END IF;
SET @cdm = DAYOFMONTH(findate);
SET @sdm = DAYOFMONTH(startdate);
SET @asd1 = TO_DAYS(startdate);
SET @asd2 = TO_DAYS(startdate);
SET @cy = YEAR(findate);
SET @sy = YEAR(startdate);
SET @cm = MONTH(findate);
SET @sm = MONTH(startdate);
SET @yy = @cy - @sy;
SET @mm = MONTH(findate) - MONTH(startdate);
CASE
WHEN @cm < @sm THEN
SET @yy = @yy - 1;
SET @mm = 12 - @sm + @cm;
WHEN @cdm >= @sdm THEN
SET @dday = @cdm - @sdm;
WHEN @cdm < @sdm THEN
label2:WHILE @sdm <> 1 DO
SET @asd2 = @asd2 + 1;
SET @sdm = DAYOFMONTH(FROM_DAYS(@asd2));
END WHILE label2;
SET @sdm = @asd2 - @asd1;
SET @dday = @cdm + @sdm - 1;
SET @mm = @mm - 1;
END CASE;
IF @mm < 0 THEN
SET @mm = 0;
END IF;
SET ddays = CONCAT(@yy, ' YEARS ', @mm, ' MONTHS ', @dday, ' DAYS.');
RETURN ddays;
END//
DELIMITER ;