我有以下SQL代码:
DELIMITER $$
CREATE FUNCTION flighttime (p_arrival(DATE), p_departure(DATE))
RETURNS CHAR(50)
BEGIN
DECLARE v_hour INT;
DECLARE v_minute INT;
DECLARE v_htext CHAR(10);
DECLARE v_mtext CHAR(10);
DECLARE v_flighttime CHAR(50);
DATEDIFF(minute, p_departure, p_arrival) AS v_minute;
v_hour = v_minute/60;
v_minute = v_minute-(v_hour*60);
IF v_hour<2 AND v_minute<2 THEN SET v_htext=' hour and ' AND v_mtext=' minute';
ELSEIF v_hour<2 AND v_minute>1 THEN SET v_htext=' hour and ' AND v_mtext=' minutes';
ELSEIF v_hour>1 AND v_minute<2 THEN SET v_htext=' hours and ' AND v_mtext=' minute';
ELSE SET v_htext=' hours and ' AND v_mtext=' minutes';
SET v_flighttime = CONCAT(v_hour, v_mtext, v_minute, v_mtext);
RETURN v_flighttime;
END
$$
DELIMITER;
校正:
DELIMITER $$
CREATE FUNCTION flighttime (p_arrival DATETIME, p_departure DATETIME)
RETURNS CHAR(70)
BEGIN
DECLARE v_hour INT;
DECLARE v_minute INT;
DECLARE v_htext CHAR(15);
DECLARE v_mtext CHAR(15);
DECLARE v_flighttime CHAR(70);
SET v_hour = HOUR(TIMEDIFF(p_departure, p_arrival));
SET v_minute = MINUTE(TIMEDIFF(p_departure, p_arrival));
IF v_hour<2 AND v_minute<2 THEN
SET v_htext = ' hour and ';
SET v_mtext=' minute';
ELSEIF v_hour<2 AND v_minute>1 THEN
SET v_htext=' hour and ';
SET v_mtext=' minutes';
ELSEIF v_hour>1 AND v_minute<2 THEN
SET v_htext=' hours and ';
SET v_mtext=' minute';
ELSE
SET v_htext=' hours and ';
SET v_mtext=' minutes';
END IF;
SET v_flighttime = CONCAT(v_hour, v_htext, v_minute, v_mtext);
RETURN v_flighttime;
END $$
DELIMITER ;
但是我在phpMyAdmin 3.5.2.2中得到了错误消息:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(DATE), p_departure(DATE)) RETURNS CHAR(50) BEGIN DECLARE v_hour INT; DECLAR' at line 1
之前我有1064个错误,并且大多能够通过使用后退滴答或正常抽搐来解决它们。不幸的是,这次它没有帮助。
此功能的目标是计算两个日期之间的差异,并以小时和分钟为单位给出差异。也是为了区分单数和复数。
如果有人为我提供解决方案或线索如何解决这个问题,我将不胜感激。
感谢您的帮助。它现在解决了(我还要将DATE更改为DATETIME :))
答案 0 :(得分:2)
您的申报无效。它应该是
CREATE FUNCTION flighttime (p_arrival DATE, p_departure DATE)
....
然后由于值设置无效,其他错误会很快上升,您应该使用SET
SET v_minute = DATEDIFF(minute, p_departure, p_arrival);
SET v_hour = v_minute/60;
SET v_minute = v_minute-(v_hour*60);
完整代码,
DELIMITER $$
CREATE FUNCTION flighttime (p_arrival DATE, p_departure DATE)
RETURNS CHAR(50)
BEGIN
DECLARE v_hour INT;
DECLARE v_minute INT;
DECLARE v_htext CHAR(10);
DECLARE v_mtext CHAR(10);
DECLARE v_flighttime CHAR(50);
SET v_minute = DATEDIFF(minute, p_departure, p_arrival);
SET v_hour = v_minute/60;
SET v_minute = v_minute-(v_hour*60);
IF v_hour<2 AND v_minute<2 THEN
SET v_htext = ' hour and ';
SET v_mtext=' minute';
ELSEIF v_hour<2 AND v_minute>1 THEN
SET v_htext=' hour and ';
SET v_mtext=' minutes';
ELSEIF v_hour>1 AND v_minute<2 THEN
SET v_htext=' hours and ';
SET v_mtext=' minute';
ELSE
SET v_htext=' hours and ';
SET v_mtext=' minutes';
END IF;
SET v_flighttime = CONCAT(v_hour, v_mtext, v_minute, v_mtext);
RETURN v_flighttime;
END $$
DELIMITER ;