mysql - 如何连接字符串并将字符串转换为日期?

时间:2012-05-21 07:20:25

标签: mysql stored-procedures

请查看我的存储过程代码。

CREATE DEFINER=`ninjaboy`@`%` PROCEDURE `getMonthlyTotalScore`(IN ninjaId int,  IN month int, IN year int)
BEGIN
    DECLARE startDate DATE;
    DECLARE endDate DATE;
    DECLARE maxDay INTEGER;

    SELECT DAY(LAST_DAY(year + '-' + month + '-01')) INTO maxDay;

    SET startDate = year + '-' + month + '-01';
    SET endDate = year + '-' + month + '-' + maxDay;

    SELECT SUM(SCORE) FROM NINJA_ACTIVITY WHERE NINJA_ID = ninjaId AND DATE BETWEEN startDate AND endDate ORDER BY DATE;
END

测试数据:

NINJA_ACTIVITY_ID | NINJA_ID | SCORE | DATE
1                   1          24      2012-05-01
2                   1          36      2012-05-06
3                   1          29      2012-05-11

函数调用:call getTotalMonthlyScore (1, 5, 2012)

我试图根据ninjaId获得任意忍者的月度分数。

为什么不工作?我知道哪里出错了?

3 个答案:

答案 0 :(得分:12)

CONCAT()是关键。

BEFORE:

mysql> CREATE  PROCEDURE `getMonthlyTotalScore`(IN ninjaId int,  IN month int, IN year int)
        -> BEGIN
        ->     DECLARE startDate DATE;
        ->     DECLARE endDate DATE;
        ->     DECLARE maxDay INTEGER;
        -> 
        ->     SELECT year + '-' + month + '-01'; #NOTE THIS
        -> 
        ->     
        -> END;    
        -> |
    Query OK, 0 rows affected (0.00 sec)

    mysql> call getMonthlyTotalScore(1,5,2012);
        -> |
    +----------------------------+
    | year + '-' + month + '-01' |
    +----------------------------+
    |                       2016 |
    +----------------------------+
    1 row in set (0.00 sec)

AFTER:

mysql> CREATE  PROCEDURE `getMonthlyTotalScore`(IN ninjaId int,  IN month int, IN year int)
    -> BEGIN
    ->     DECLARE startDate DATE;
    ->     DECLARE endDate DATE;
    ->     DECLARE maxDay INTEGER;
    -> 
    ->     SELECT CONCAT(year,'-',month,'-01'); # NOTE THIS
    -> 
    ->     
    -> END;    |
Query OK, 0 rows affected (0.00 sec)

mysql> call getMonthlyTotalScore(1,5,2012);
    -> |
+------------------------------+
| CONCAT(year,'-',month,'-01') |
+------------------------------+
| 2012-5-01                    |
+------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

答案 1 :(得分:2)

而不是:

SELECT DAY(LAST_DAY(year + '-' + month + '-01')) INTO maxDay;

替换为

SET maxDay := DAY(LAST_DAY(CAST(CONCAT(year, '-',month,'-01) as DateTime)));

答案 2 :(得分:0)

从beck的答案中得到这个想法后,我有了这个有效的解决方案。

CREATE DEFINER=`ninjaboy`@`localhost` PROCEDURE `getMonthlyTotalScore`(IN ninjaId int,  IN month int, IN year int)
BEGIN
    DECLARE startDate DATE;
    DECLARE endDate DATE;
    DECLARE maxDay INTEGER;

    SELECT DAY(LAST_DAY(CONCAT(year,'-',month,'-01'))) INTO maxDay;

    SET startDate =  CONCAT(year,'-',month,'-01');
    SET endDate = CONCAT(year,'-',month,'-',maxDay);

    SELECT SUM(SCORE) FROM NINJA_ACTIVITY WHERE NINJA_ID = ninjaId AND DATE BETWEEN startDate AND endDate ORDER BY DATE;
END