gpt4 book ai didi

MySQL - 函数中从 'yyyy-mm-mm' 到 'yyyy-mm' 的日期格式

转载 作者:行者123 更新时间:2023-11-29 23:23:20 28 4
gpt4 key购买 nike

我创建了一个函数,它以与原始格式不同的格式返回日期。基本上,我正在使用此 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;

最佳答案

如果我理解正确,您希望函数执行的操作是:

  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 |

关于MySQL - 函数中从 'yyyy-mm-mm' 到 'yyyy-mm' 的日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139669/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com