PostgreSQL - Iterate over results of query
temprow
is a record variable which is bound in turn to each record of the first SELECT
.
So you should write:
FOR temprow IN
SELECT * FROM user_data.users ORDER BY user_seasonpts DESC LIMIT 10
LOOP
INSERT INTO user_data.leaderboards (season_num,player_id,season_pts) VALUES (old_seasonnum,temprow.userd_id,temprow.season_ptss);
END LOOP;
This loop could be further simplified as a single query:
INSERT INTO user_data.leaderboards (season_num,player_id,season_pts)
SELECT old_seasonnum,player_idd,season_ptss FROM user_data.users ORDER BY user_seasonpts DESC LIMIT 10
A function that loop through the select and use loop item values to filter and calculate other values,
CREATE FUNCTION "UpdateTable"() RETURNS boolean
LANGUAGE plpgsql
AS
$$
DECLARE
TABLE_RECORD RECORD;
BasePrice NUMERIC;
PlatformFee NUMERIC;
MarketPrice NUMERIC;
FinalAmount NUMERIC;
BEGIN
FOR TABLE_RECORD IN SELECT * FROM "SchemaName1"."TableName1" -- can select required fields only
LOOP
SELECT "BasePrice", "PlatformFee" INTO BasePrice, PlatformFee
FROM "SchemaName2"."TableName2" WHERE "UserID" = TABLE_RECORD."UserRID";
SELECT "MarketPrice" / 100 INTO MarketPrice FROM "SchemaName3"."TableName3" WHERE "DateTime" = TABLE_RECORD."DateTime";
FinalAmount = TABLE_RECORD."Qty" * (BasePrice + PlatformFee - MarketPrice);
UPDATE "SchemaName1"."TableName1" SET "MarketPrice" = MarketPrice, "Amount" = CFDAmount
WHERE "ID" = CFD_RECORD."ID"; -- can update other schema tables also
END LOOP;
RETURN TRUE;
END
$$;