【发布时间】:2021-08-14 20:41:33
【问题描述】:
我想创建一个临时表并利用一个变量。我查阅了文档,我相信语法是正确的,但是将它们放在一起会给我一个错误。
我的目标是创建一个日期变量,该变量始终比 now() 早 1 年,并将在我的临时表中填充一个月增量行,直到现在。任何帮助将不胜感激。
错误:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @start_date = DATEADD(year, -1 ,GETDATE())\n\n WHILE @start_date < GETD' at line 4"
这是我的 SQL 语句。
CREATE TEMPORARY TABLE helper(
date datetime not null
);
SET @start_date = DATEADD(year, -1 ,GETDATE())
WHILE @start_date < GETDATE()
BEGIN
INSERT INTO helper VALUES (@start_date)
SELECT @start_date = DATEADD(MONTH, 1, @start_date)
END
更新 1
使用此代码,我仍然收到语法错误
CREATE TEMPORARY TABLE helper(
date datetime not null
);
insert into helper (date)
with recursive cte as (
select curdate() - interval 12 month as date
union all
select date + interval 1 month
from cte
where date < curdate()
)
select date from cte;
select * from helper;
错误
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into helper (date)\n with recursive cte as (\n select c' at line 4",
更新 2
我已将语法更改为此。我仍然收到错误,但它似乎更接近 mySql 5.7
`
CREATE TEMPORARY TABLE helper(
date datetime not null
);
CREATE PROCEDURE dowhile()
BEGIN
DECLARE date datetime DEFAULT SUBDATE(curdate(), interval 12 month);
WHILE date < curDate() DO
INSERT INTO helper VALUES(date);
SET date = date + interval 1 month;
END WHILE;
END;
DELIMITER;
CALL dowhile()
SELECT date_format(log.entry_stamp, '%Y-%M') AS 'date', COUNT(log.element_id) as count FROM dm_log log
INNER JOIN dm_element el
ON el.element_id = log.element_id
WHERE ? = el.dm_id
LEFT OUTER JOIN helper h
ON h.date = log.date
GROUP BY date
ORDER BY date;
DROP TEMPORARY TABLE helper;
`
错误
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE PROCEDURE dowhile()\n BEGIN\n DECLARE date datetime DEFAU' at line 4",
【问题讨论】:
标签: mysql sql database syntax backend