I have a table through which I'm iterating a for loop and while trying to update the source table data inside the for loop, it's not reflecting. In the below example I want the RASIE NOTICE statement should execute 5 times but it's only executing 3 times.
DO $$
DECLARE p_Id int;
BEGIN
DROP TABLE IF EXISTS TempTbl;
CREATE TEMPORARY TABLE TempTbl (Id int);
INSERT INTO TempTbl VALUES (1);
INSERT INTO TempTbl VALUES (2);
INSERT INTO TempTbl VALUES (3);
FOR p_Id in SELECT * FROM TempTbl
LOOP
RAISE NOTICE 'Value of p_Id: %', p_Id;
INSERT INTO TempTbl
SELECT 4
WHERE 4 NOT IN (SELECT Id FROM TempTbl);
INSERT INTO TempTbl
SELECT 5
WHERE 5 NOT IN (SELECT Id FROM TempTbl);
END LOOP;
END $$;
Current Output
NOTICE: Value of p_Id: 1
NOTICE: Value of p_Id: 2
NOTICE: Value of p_Id: 3
Expected Output
NOTICE: Value of p_Id: 1
NOTICE: Value of p_Id: 2
NOTICE: Value of p_Id: 3
NOTICE: Value of p_Id: 4
NOTICE: Value of p_Id: 5
Note: I would be retrieving the values 4 and 5 from the first 3 rows (i.e., I can't insert all the values at the beginning).