Domanda

I tried some, but I couldn't find the solution, somehow I managed to get this result.

Here is the query:

DELIMITER ##
CREATE PROCEDURE test1(start_date DATE,end_date DATE)
BEGIN
   DECLARE done INT DEFAULT FALSE;   
   DECLARE a INT;
   DECLARE present INT;
   DECLARE total INT;
   -- Declare the cursor
   DECLARE id CURSOR
   FOR
   SELECT staff_id FROM ost_staff;
   DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
   -- Open the cursor
   DROP TEMPORARY TABLE IF EXISTS reports;
   CREATE TEMPORARY TABLE IF NOT EXISTS reports
   (
    staff_id INT(10),
    present INT(10),
total INT(10)
   );
   OPEN id;
   read_loop: LOOP
   FETCH id INTO a;
   IF done THEN
   LEAVE read_loop;
   END IF;
   INSERT INTO reports(staff_id,present,total)
   SELECT (COUNT(I.interval_start)) AS present, DATEDIFF(DATE_ADD(end_date,INTERVAL 1     DAY),start_date) AS total
    FROM effort_frequency E 
RIGHT OUTER JOIN time_intervals I ON I.interval_start = E.log_date 
AND E.staffid=a AND E.log_date BETWEEN start_date AND end_date
LEFT OUTER JOIN ost_holidays H ON H.holiday_date = I.interval_start
WHERE DATE_FORMAT(I.interval_start,'%a') = 'Sun' OR H.holiday_date = I.interval_start OR E.total_effortspent IS NOT NULL;

   -- Close the cursor   
   END LOOP;
   CLOSE id;
END ##

I got the below result:

+----------+-----------------+
| staff_id | present | total |
+----------+---------+-------+
|  (NULL)  |   23    |  24   |
|  (NULL)  |   22    |  24   |
+----------+---------+-------+

I'm getting (NULL) for staff_id, How can I get the staff_id's there ? I tried using declared variable 'a' in insert statement, but at that time I got only staff_id, I didn't get the other 2 fields, I can't get the staff_id from the select inside insert statement coz there is some problem.

Now what i need is I need to insert the staff_id from the variable 'a' into that temporary table.

note: I'm really new to this stored procedure, but somehow managed till here, Its good if I get some detail on how to use the Select inside Insert including the solution for this.

È stato utile?

Soluzione

Try this -

SELECT a, (COUNT(I.interval_start)) AS present, DATEDIFF(DATE_ADD(end_date,INTERVAL 1     DAY),start_date) AS total

Altri suggerimenti

Your INSERT requires three fields, but your SELECT statement only selects two: present and total .

Try:

 SELECT E.staffid, (COUNT(I.interval_start)) 
 AS present, DATEDIFF(DATE_ADD(end_date,INTERVAL 1 DAY),start_date) AS total
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top