开发者

mysql stored function usage

I just wrote a stored function to calculate the working days between two dates. This works

select CountWeekDays('2010-03-07','2010-04-07')

This doesn't work

select CountWeekDays(o.order_date,o.created_date) from orders o;

Any idea how to make this one work ??

function definition

delimiter $$;

CREATE FUNCTION CountWeekDays (sdate VARCHAR(50), edate VARC开发者_运维技巧HAR(50)) RETURNS INT

BEGIN

DECLARE wdays, tdiff, counter, thisday smallint;

DECLARE newdate DATE;

SET newdate := sdate;

SET wdays = 0;

if DATEDIFF(edate, sdate) = 0 THEN RETURN 1; END IF;

if DATEDIFF(edate, sdate) < 0 THEN RETURN 0; END IF;

label1: LOOP

SET thisday = DAYOFWEEK(newdate);

IF thisday BETWEEN 2 AND 6 THEN SET wdays := wdays + 1; END IF;

SET newdate = DATE_ADD(newdate, INTERVAL 1 DAY);

IF DATEDIFF(edate, newdate) < 0 THEN LEAVE label1; END IF;

END LOOP label1;

RETURN wdays;

END


I don't much about functions but try if it works, sorry if not works.

select CountWeekDays(o.order_date,o.created_date) from orders o where o.id =1;


It had something to do with datatype .. following function worked fine ..

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%' ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜