我刚写了一个存储函数来计算两个日期之间的工作日。 这工作
选择 CountWeekDays( '2010-03-07', '2010-04-07')
这不起作用
选择 CountWeekDays(o.order_date,o.created_date) 来自订单o;
任何想法如何使这个工作?
功能定义
delimiter $$;
创建功能
CountWeekDays
(sdate VARCHAR(50),edate VARCHAR(50)) 退货INTBEGIN
DECLARE wdays,tdiff,counter,今天 SMALLINT;
DECLARE newdate DATE;
SET newdate:= sdate;
SET wdays = 0;
如果DATEDIFF(edate,sdate)= 0那么 返回1;结束如果;
如果DATEDIFF(edate,sdate)< 0那么 返回0;结束如果;
label1:LOOP
SET thisday = DAYOFWEEK(newdate);
如果这一天在2和6之间,那么设置 wdays:= wdays + 1;结束如果;
SET newdate = DATE_ADD(newdate, INTERVAL 1天;
IF DATEDIFF(edate,newdate)< 0那么 LEAVE label1;结束如果;
END LOOP label1;
返回wdays;
END
答案 0 :(得分:0)
我对功能并不多,但试试它是否有效,抱歉,如果不起作用。
select CountWeekDays(o.order_date,o.created_date) from orders o where o.id =1;
答案 1 :(得分:0)
它与数据类型有关..以下函数工作正常..
SET GLOBAL log_bin_trust_function_creators=1;
DROP FUNCTION IF EXISTS BizDaysInclusive;
DELIMITER |
CREATE FUNCTION BizDaysInclusive( d1 DATE, d2 DATE )
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE dow1, dow2, days INT;
SET dow1 = DAYOFWEEK(d1);
SET dow2 = DAYOFWEEK(d2);
SET days = FLOOR( DATEDIFF(d2,d1)/7 ) * 5 +
CASE
WHEN dow1=1 AND dow2=7 THEN 5
WHEN dow1 IN(7,1) AND dow2 IN (7,1) THEN 0
WHEN dow1=dow2 THEN 1
WHEN dow1 IN(7,1) AND dow2 NOT IN (7,1) THEN dow2-1
WHEN dow1 NOT IN(7,1) AND dow2 IN(7,1) THEN 7-dow1
WHEN dow1<=dow2 THEN dow2-dow1+1
WHEN dow1>dow2 THEN 5-(dow1-dow2-1)
ELSE 0
END;
RETURN days;
END;
|
DELIMITER ;
SELECT BizDaysInclusive('2009-8-1','2009-9-15');
select substr(o.order_date,1,10) a ,substr(o.created_date,1,10) b, CountWeekDays(substr(o.order_date,1,10),substr(o.created_date,1,10)) c from orders o WHERE o.order_date like '2010-04-08%' ;