我有这个小桌子,里面只有“fecha”字段。
我需要一个MySQL
查询,将每年的星期日和星期六插入到表中。
我自己的研究让我知道我需要做这样的事情:
DECLARE diaRecorrido date();
SET diaRecorrido = date(now());
WHILE DATEPART(WEEKDAY,diaRecorrido) = 1 or DATEPART(WEEKDAY,diaRecorrido) = 7
BEGIN
INSERT INTO feriados (fecha)
VALUES (diaRecorrido)
IF diaRecorrido=2017/01/01
THEN
LEAVE lazo;
END IF;
END;
任何指导都非常苛刻!
答案 0 :(得分:2)
我认为你应该使用DAYOFWEEK()
create PROCEDURE generateSundayAndSaturday()
BEGIN
DECLARE _now DATETIME;
DECLARE _endYear DATETIME;
SET _endYear = DATE_FORMAT(NOW() + INTERVAL 1 YEAR ,'%Y-01-01');
SELECT now() into _now from dual;
while _now < _endYear DO
if DAYOFWEEK(_now) = 7 THEN -- Saturday
-- insert into
SET _now = _now + INTERVAL 1 DAY;
ELSEIF DAYOFWEEK(_now) = 1 THEN -- Sunday
-- insert into
SET _now = _now + INTERVAL 6 DAY;
ELSE
SET _now = _now + INTERVAL 1 DAY;
END IF;
END WHILE;
END;
答案 1 :(得分:0)
您可以创建一个数字表格,然后从中选择您希望保留的年份日期:
DECLARE @Date1 DATE, @Date2 DATE
SET @Date1 = '20160101'
SET @Date2 = '20161231'
INSERT INTO feriados
SELECT DATEADD(DAY,number+1,@Date1) [Date]
FROM master..spt_values
WHERE type = 'P' AND
DATEADD(DAY,number+1,@Date1) < @Date2 AND
(DATEPART(WEEKDAY, DATEADD(DAY,number+1,@Date1)) = 1 OR
DATEPART(WEEKDAY, DATEADD(DAY,number+1,@Date1)) = 7)
答案 2 :(得分:0)
这是MS SQL(t-sql)查询。我认为你可以修复MySQL的小语法差异。
declare @thisYear datetime=cast(year(getdate()) as varchar)+'-01-01',
@newyear datetime=cast(year(getdate())+1 as varchar)+'-01-01'
declare @frstSat datetime, @frstSun datetime
select @frstSat= dateadd(dd,7-DATEPART(weekday,@thisYear),@thisYear) ,
@frstSun= case DATEPART(weekday,@thisYear)
when 1 then @thisYear --if 1/1 is Sunday
else dateadd(dd,8-DATEPART(weekday,@thisYear),@thisYear) end
;with sat as (
select @frstSat dt,'Sat' WkDay
union all
select dateadd(dd,7,dt),'Sat' WkDay
from sat
where dateadd(dd,7,dt)<@newyear
)
,sun as (
select @frstSun dt,'Sun' WkDay
union all
select dateadd(dd,7,dt),'Sun' WkDay
from sun
where dateadd(dd,7,dt)<@newyear
)
--insert mytable
select * from sat
union
select * from sun
order by dt