我在MySQL中写了一个Stored Procedure
。
我试图分别在任何一个月的专栏中获得几天。
下面的是sql query
DELIMITER $$
DROP PROCEDURE IF EXISTS `GenerateReport`$$
CREATE
DEFINER = `FreeUser`@`localhost`
PROCEDURE `databasename`.`GenerateReport`(
IN gDate DATE,
IN gUserID VARCHAR(10)
)
BEGIN
DECLARE gStart INT;
DECLARE gDays INT;
SET gStart = 1;
SET gDays = DAY(LAST_DAY(gDate));
SELECT e.AssociateID, CONCAT(e.FirstName, ' ', e.MiddleName, ' ', e.LastName) AS `EmployeeName`, d.DesignationName,
ts.TSDate,
/* Trying to get days in column, Starts here */
loopOne: LOOP
IF gStart <= gDays THEN
gStart = gStart + 1;
case gStart IS NOT NULL THEN 'ItsDate' ELSE 'NoDate' END,
ITERATE loopOne;
END IF;
LEAVE loopOne;
END LOOP loopOne;
/* Trying to get days in column, ends here */
gStart AS `Start`, gDays AS `NoofDays`
FROM timesheet ts
LEFT JOIN employee e ON e.EmpID = ts.EmpID
LEFT JOIN designation d ON d.DesignationId = e.DEsignationID
WHERE DATE_FORMAT(ts.TSDate, '%Y-%m') = DATE_FORMAT(gDate, '%Y-%m')
GROUP BY e.AssociateID;
END$$
DELIMITER ;
考虑额外UI的图像,下面可能不是很好的respresntation
----------------------------------------------------------
AssociateID | EmployeeName | DesignationName | 1 | 2 | 3 | 4 | .... | 31 | Start | gDays
---------------------------------------------------------
001 |John Carter | Dae ja | ItsDate | ItsDate| .... | ItsDate | 1 | 31
----------------------------------------------------------------------------------
答案 0 :(得分:1)
无法构建与循环混合的查询,if语句或任何其他流控制。
您需要构建一个动态预准备语句然后执行它。
drop procedure if exists dynamiccolumns;
delimiter //
create procedure dynamiccolumns()
begin
declare v_count int default 1;
set @ps := 'select now()';
oneToTen: loop
if v_count = 10 then
leave oneToTen;
end if;
set @ps := concat(@ps, ", ");
set @ps := concat(@ps, v_count);
set v_count := v_count + 1;
end loop oneToTen;
set @ps := concat(@ps, " from dual");
prepare ps from @ps;
execute ps;
deallocate prepare ps;
end//
delimiter ;
并称之为
mysql> call dynamiccolumns;
+---------------------+---+---+---+---+---+---+---+---+---+
| now() | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---------------------+---+---+---+---+---+---+---+---+---+
| 2013-07-10 06:11:43 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+---------------------+---+---+---+---+---+---+---+---+---+
1 row in set (0.00 sec)