使用declare语法错误

时间:2012-10-22 17:14:25

标签: mysql sql

使用“declare”时出现语法错误:

 delimiter $$
  begin

 declare @StartDay INT, @EndDay INT, @StartMonth INT, @EndMonth INT
 Select @StartDay = 01, @StartMonth = 10, @EndDay = 30, @EndMonth = 09

 Select year(a.created_at) as years , jd.JobDomain, count(a.Id) as nb_answer,   a.Job_id,   j.JobTitle 
 from JobAppliance a
 inner join Job j on a.Job_id =  j.PublicId
 inner join JobDestination d on j.Id=d.Job_id
 inner join Jjobdomain jd on  j.Id = jd.Job_id

 and 
 (
 @StartMonth = @EndMonth And 
 Month(a.created_at) = @StartMonth And 
 Day(a.created_at) >= @StartDay And 
 Day(a.created_at) <= @EndDay
 ) Or (
 @StartMonth != @EndMonth And (
 (
 Month(a.created_at) = @StartMonth And
 Day(a.created_at) >= @StartDay
 ) Or (
 Month(a.created_at) Between @StartMonth + 1 And @EndMonth - 1
 ) Or (
 Month(a.created_at) = @EndMonth And
 Day(a.created_at) <= @EndDay
 )
 )
)

group by year(a.created_at) , a.Job_id, j.JobTitle;

end$$
delimiter ;

我正在使用Mysql workbench

编辑:

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 
'@StartDay int, @EndDay int, @StartMonth int, 
     @EndMonth intSelect @StartDay = 0' at line 3

1 个答案:

答案 0 :(得分:1)

你错过了行分隔符

DELIMITER $$

DECLARE MyVal INT$$

SELECT
...
$$

DELIMITER ;

另一方面,你为什么要更改分隔符?

并且声明只应在文档中所述的BEGIN和END之间使用。 因此,如果您未在存储过程中使用此部件(例如,简单查询),则无法使用DECLARE

以@开头的所有变量都是会话变量,不需要声明。

所以这里有一个拷贝'n'糊涂你

SET @StartDay = 01, @StartMonth = 10, @EndDay = 30, @EndMonth = 09; -- look here the ;

Select year(a.created_at) as years , jd.JobDomain, count(a.Id) as nb_answer,   a.Job_id,   j.JobTitle 
from JobAppliance a
inner join Job j on a.Job_id =  j.PublicId
inner join JobDestination d on j.Id=d.Job_id
inner join Jjobdomain jd on  j.Id = jd.Job_id

and 
(
@StartMonth = @EndMonth And 
Month(a.created_at) = @StartMonth And 
Day(a.created_at) >= @StartDay And 
Day(a.created_at) <= @EndDay
) Or (
@StartMonth != @EndMonth And (
(
Month(a.created_at) = @StartMonth And
Day(a.created_at) >= @StartDay
) Or (
Month(a.created_at) Between @StartMonth + 1 And @EndMonth - 1
) Or (
Month(a.created_at) = @EndMonth And
Day(a.created_at) <= @EndDay
)
)
)

group by year(a.created_at) , a.Job_id, j.JobTitle;