开发者

Struggling to see the error of my ways (mysql function)

开发者 https://www.devze.com 2023-02-05 15:27 出处:网络
(see my answer below for solution - thanks for the feedback) It\'s probably something really obvious but I can\'t see what\'s wrong with my sql:

(see my answer below for solution - thanks for the feedback)

It's probably something really obvious but I can't see what's wrong with my sql:

mysql> CREATE FUNCTION start_of_minute(
->     curdate DATE)
->   RETURNS DATE
->   DETERMINISTIC
->   SQL SECURITY INVOKER
->开发者_如何学JAVA   BEGIN
->     DECLARE sofm DATE;
->     SET sofm = SUBDATE (
->         curdate,
->         INTERVAL SECOND(curdate) SECOND
->       );
->   RETURN sofm;
->   END //
ERROR 1064 (42000): 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 ');
RETURN sofm;
END' at line 11

All the more frustrating as the following works:

mysql> CREATE FUNCTION start_of_week(
->     curdate DATE,
-> first_day_of_week INTEGER)
->    RETURNS DATE
->    DETERMINISTIC
->    SQL SECURITY INVOKER
->    BEGIN
->       DECLARE sow DATE;
->       SET sow = SUBDATE(
->         curdate,
->         INTERVAL (WEEKDAY(curdate)+(7-first_day_of_week)%7) DAY
->         );
->       RETURN sow;
->    END //
Query OK, 0 rows affected (0.00 sec)

(NB there may be other ways of truncating the date at various levels - and I'd certainly be interested in hearing about them, I really want to know what's wrong with my syntax - not a different method for calculating the start of a period).

Yes, second() is a valid function, and SECOND is a valid interval.

TIA


I had already considered that it was getting upset about the types - however replacing all the 'date' types with 'DATETIME' types did not resolve the problem - turns out the problem was a space between 'SUBDATE' and '(' - I never knew MySQL was fussy about such things!

(I'd flag this as an asnwer but SO wants me to wait a couple of days first)


curdate is a reserved word:

drop function if exists start_of_minute;

delimiter #

create function start_of_minute
(
p_curdate datetime
)
returns datetime
begin
declare sofm datetime;
  set sofm = subdate(p_curdate, interval second(p_curdate) second);
  return sofm;
end#

delimiter;
select now(), start_of_minute(now());

EDIT

mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2011-01-17 |
+------------+
1 row in set (0.00 sec)


The problem is because the function second() take in time instead of date

maybe like this

second( cast(curdate as time) )

BUT

is meaningless due to sub-date for a given date to seconds, and return in date format (which still a date)


Should you not use a DATETIME data type rather than DATE?

0

精彩评论

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