日期变量未在存储过程中正确传递。 此部分返回null
(CONVERT_TZ( (FROM_UNIXTIME(@fromDate/1000)),''UTC'', @timeZone) )AS startingDate,
(CONVERT_TZ( (FROM_UNIXTIME(@toDate/1000)),''UTC'', @timeZone) ) AS endingDate,
这些日期显示为空
l1.started BETWEEN @startDate AND @endDate
我错过了这些值没有传递给查询
CREATE PROCEDURE reportFreeCoolingTrackerTest (
IN fromDate varchar (50),
IN toDate varchar (50),
IN timeZone varchar (50))
BEGIN
DECLARE startDate varchar (50);
DECLARE endDate varchar (50);
DECLARE mylogID Int;
SET startDate = FROM_UNIXTIME(fromDate/1000);
SET endDate = FROM_UNIXTIME(toDate/1000);
SET mylogID = (SELECT logID FROM logs l WHERE l.details LIKE 'FCT%');
SET @tbl = CONCAT('log',mylogID);
set @q1 = CONCAT('SELECT
i.details,l1.item31985,l1.item31987,
((l1.item31985 - l1.item31987)*(time_to_sec(timediff(t2.completed, l1.completed)))) / 3600 AS kwDifference,
((l1.item31985 - l1.item31987) * (substr(l.details, instr(l.details , '':'' ) +1))) AS cost,
(((l1.item31985 - l1.item31987) * (substr(l.details, instr(l.details , '':'' ) +1)))
*(time_to_sec(timediff(t2.completed, l1.completed)) / 3600)) AS costT,
time_to_sec(timediff(t2.completed, l1.completed)) / 3600 AS coolingHours,
time_to_sec(timediff(@endDate, @startDate)) / 3600 AS totalTimeRange,
(CONVERT_TZ( (FROM_UNIXTIME(@fromDate/1000)),''UTC'', @timeZone) )AS startingDate,
(CONVERT_TZ( (FROM_UNIXTIME(@toDate/1000)),''UTC'', @timeZone) ) AS endingDate,DATABASE() AS databaseName,
CASE
when l1.activityId = t2.activityId THEN 1
ELSE 0
END AS errorCheck, t2.completed AS errorDay,a.scheduleType,@lgName,@mylogID
FROM logs l
INNER JOIN groups g ON g.groupId = l.groupId
LEFT JOIN groups g1 ON g.parentId = g1.groupId
LEFT JOIN groups g2 ON g1.parentId = g2.groupId
LEFT JOIN groups g3 ON g2.parentId = g3.groupId
INNER JOIN activities a ON l.logId = a.logId
INNER JOIN ', @tbl,' l1 ON a.activityId = l1.activityId ');
set @q2 = CONCAT(@q1, 'INNER JOIN ', @tbl);
SET @q3 = CONCAT(@q2, ' t2 ON t2.recordId = l1.recordid + 1
INNER JOIN items i ON l.logId = i.logId AND i.name LIKE ''%KW%''
INNER JOIN users u ON l1.userId = u.userId AND i.name LIKE ''%KW%''
WHERE i.itemID = "31985" AND l1.activityId = 1257
AND l1.started
BETWEEN @startDate
AND @endDate
ORDER BY l1.recordId,l1.started');
PREPARE stmt FROM @q3;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
答案 0 :(得分:0)
您的代码存在许多问题。以下是主要内容:
您将过程输入参数和局部变量与用户(会话)变量混合在一起。例如。你有一个输入参数fromDate
,但你在查询@fromDate
中引用它是用户(会话)变量并且与参数无关。这就是为什么你得到NULL
而不是实际值。
不是将查询字符串与变量值连接,而是将变量名称作为字符串文字的一部分。
在查询字符串中插入日期字符串文字(例如变量fromDate
和startDate
)时应引用它们。同样适用于timeZone
值。
在您的查询字符串中,您指的是@lgName
变量,该变量很可能不包含任何值。即使它确实然后通过用户(会话)变量传递它,你应该通过另一个过程参数完成它。
这部分
SET mylogID = (SELECT logID FROM logs l WHERE l.details LIKE 'FCT%');
应返回唯一的值,否则会破坏您的代码。使用LIKE
可以轻松生成多行。这就是说应用LIMIT 1
(或聚合函数,例如MIN()
或MAX
)或使用基于具有(具有)PK或{的列的条件重写它{1}}约束。
UNIQE
,fromDate
,startDate
是局部变量。但由于某种原因,您使用用户变量mylogID
来保存表名值。抛弃它,只需在构建查询字符串时连接@tbl
和'log'
值。
据说你的程序看起来像
mylogID
这是 SQLFiddle 演示,显示最终查询字符串而不是执行它