MySQL資料庫生成某一年的日曆儲存過程

2022-07-11 08:57:12 字數 2435 閱讀 6703

delimiter $$

create procedure `t_base_calender` ( in year varchar ( 20) ) begin

declare

i int;

declare

start_date varchar ( 20);

declare

end_date varchar ( 20);

declare

date_count int;

set i = 0;

set start_date = concat( year, '-01-01');

set end_date = concat( year + 1, '-01-01');

set date_count =datediff( end_date, start_date );

while

i insert into t_base_calender ( day_time, day_week, day_type ) select

date_format( str_to_date( start_date, '%y-%m-%d %h:%i:%s' ), '%y-%m-%d') day_time,

dayofweek( str_to_date( start_date, '%y-%m-%d %h:%i:%s') ) day_week,

//注意這裡的週幾會多1天,如應該是周五,會是週六。需特殊處理

case

dayofweek( str_to_date( start_date, '%y-%m-%d %h:%i:%s') )

when 6then

2when 7then

2 else 1end day_type

from

dual;

set i = i + 1;

set start_date = date_format( date_add( str_to_date( start_date, '%y-%m-%d %h:%i:%s' ), interval 1 day ), '%y-%m-%d');

end while;

end

改良之後:

delimiter $$

create procedure `t_base_calender` ( in year varchar ( 20) ) begin

declare

i int;

declare

start_date varchar ( 20);

declare

end_date varchar ( 20);

declare

date_count int;

set i = 0;

set start_date = concat( year, '-01-01');

set end_date = concat( year + 1, '-01-01');

set date_count =datediff( end_date, start_date );

while

i insert into t_base_calender ( day_time, day_week, day_type ) select

date_format( str_to_date( start_date, '%y-%m-%d %h:%i:%s' ), '%y-%m-%d') day_time,

case

dayofweek( str_to_date( start_date, '%y-%m-%d %h:%i:%s' ) ) - 1when 0then

7 else dayofweek( str_to_date( start_date, '%y-%m-%d %h:%i:%s' ) ) - 1end day_week,

case

dayofweek( str_to_date( start_date, '%y-%m-%d %h:%i:%s') )

when 7then

2when 1then

2 else 1end day_type

from

dual;

set i = i + 1;

set start_date = date_format( date_add( str_to_date( start_date, '%y-%m-%d %h:%i:%s' ), interval 1 day ), '%y-%m-%d');

end while;

end

執行儲存過程:

call t_base_calender('2021');

刪除儲存過程:

drop procedure t_base_calender;

注:mysql的儲存過程語句之前要加 delimiter $$ 否則會報 declare 定義變數報錯。

mysql 查詢某一年 某一月 某一天的資料

查詢某一年 某一月 某一天的資料 可組合 select fromymt where date format indate,y m d 2016 10 10 indate為表中列名 mysql查詢一天,查詢一周,查詢乙個月內的資料 查詢一天 select from ymt where date ind...

Mysql中查詢某一天,某個月,某一年資料

今天 select from 表名 where to days 時間欄位名 to days now 昨天 select from 表名 where to days now to days 時間欄位名 1近7天 select from 表名 where date sub curdate interva...

一鍵匯入一年日期到資料庫

controller層 public class workdaycontroller 匯入一年資料資訊 根據日期查詢日期狀態 根據日期修改日期型別狀態 起始時間和結束時間判斷 param date return private static listdatesplit date start,date...