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
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 DEFAULT 0; /* Счетчик дней до 1 числа след месяца */
/* Проверка на порядок дат */
IF findate < startdate THEN
SET startdate = fndate;
SET findate = strtdate;
END IF;
SET @currdayofmonth = DAYOFMONTH(findate);
SET @startdayofmonth = DAYOFMONTH(startdate);
SET @asd1 = TO_DAYS(startdate);
SET @curryear = YEAR(findate);
SET @startyear = YEAR(startdate);
SET @currmonth = MONTH(findate);
SET @startmonth = MONTH(startdate);
SET @yy = @curryear - @startyear;
SET @mm = MONTH(findate) - MONTH(startdate);
CASE
WHEN @currmonth < @startmonth THEN
SET @yy = @yy - 1;
SET @mm = 12 - @startmonth + @currmonth;
WHEN @currdayofmonth >= @startdayofmonth THEN
SET @dday = @currdayofmonth - @startdayofmonth;
WHEN @currdayofmonth < @startdayofmonth THEN
label2:WHILE DAYOFMONTH(FROM_DAYS(@asd1)) <> 1 DO
SET @asd1 = @asd1 + 1;
SET counterdays = counterdays + 1;
END WHILE label2;
SET @dday = @currdayofmonth + counterdays - 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 ;