【问题标题】:MySQL - Date Format from 'yyyy-mm-mm' to 'yyyy-mm' in a functionMySQL - 函数中从“yyyy-mm-mm”到“yyyy-mm”的日期格式
【发布时间】:2014-11-26 01:08:17
【问题描述】:

我创建了一个函数,它以与原始格式不同的格式返回日期。 基本上,我正在使用这个Select MonthSub('2014-04-10',2)# 语句进行测试,它应该返回 2014-02,而不是2014-02-10

有人可以检查我的代码,看看我做错了什么吗? 如果我使用date_format(new_in_date, '%y-%m') 对格式进行任何操作,则会返回此错误:

ERROR 1292 (22007): Incorrect date value: '2014-02' for column 'new_in_date' at row 1

我写的函数:

Create function MonthSub (in_date date, in_mn_adjust int)
    returns date
Begin
    declare new_in_date date default in_date;
    set new_in_date := date_sub(new_in_date, interval in_mn_adjust month);
    return new_in_date;
end;

【问题讨论】:

  • 您的意思是标题中的 yyyy-mm-dd?
  • 你想要的是,给定一个日期,减去月数,只返回年月。我理解正确吗? (例如:MonthSub('2014-04-10', 2) 表示“减去两个月并仅返回 yyyy-mm;在本例中为 2014-02
  • 如果要在函数中使用date_format,需要returns varchar

标签: mysql date format


【解决方案1】:

如果我理解正确的话,你希望你的函数做的是:

  1. 给定一个日期d 和一个数字n,您想将n 月减去d
  2. 那么你只想返回日期的年月

因此,您可以执行以下操作:

SQL Fiddle

MySQL 5.5.32 架构设置

create function MonthSub(d date, n int) 
returns varchar(50) -- You're not returning a date, but a string 
                    -- ('yyyy-mm' is not a date)
begin
  declare t date;
  declare ans varchar(50);
  set t = date_add(d, interval -(day(d)-1) day); -- Substract the days 
                                                 -- to avoid problems with things 
                                                 -- like 'February 30th'
  set t = date_add(t, interval -n month); -- Substract the months
  set ans = date_format(t, '%Y-%m'); -- Format the date to 'yyyy-mm'
  return ans; -- Return the date
end //

查询 1

-- Test it!
select MonthSub('2014-05-02', 2)

Results

| MONTHSUB('2014-05-02', 2) |
|---------------------------|
|                   2014-03 |

【讨论】:

  • 啊!!是的,这很棒。我想过把它变成字符串,然后觉得它有点牵强..我想这是一种方法。非常感谢!!!
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多