简体   繁体   中英

using PERFORM to insert a string of SELECT statement into a temp table

I am trying to insert data into a temp_table and then truncating the table after analyzing the result.

Here is my code:

CREATE OR REPLACE FUNCTION validation()
  RETURNS text AS $$
DECLARE counter INTEGER;
DECLARE minsid INTEGER;
DECLARE maxsid INTEGER;
DECLARE rec RECORD;
DECLARE stmt varchar;
BEGIN
  SELECT MIN(sid) INTO minsid FROM staging.validation;
  SELECT MAX(sid) INTO maxsid FROM staging.validation;

  CREATE TEMPORARY TABLE temp_table (col1 TEXT, col2 INTEGER, col3 BOOLEAN) ON COMMIT DROP;

  FOR counter IN minsid..maxsid LOOP
    RAISE NOTICE 'Counter: %', counter;
    SELECT sql INTO stmt FROM staging.validation WHERE sid = counter;

    RAISE NOTICE 'sql: %', stmt;

    PERFORM 'INSERT INTO temp_table (col1, col2, col3) ' || stmt;

    IF temp_table.col3 = false THEN
      RAISE NOTICE 'there is a false value';
    END IF;

  END LOOP;
END; $$
LANGUAGE plpgsql;

Whenever I run this function SELECT * FROM validation(); I get an error:

ERROR: missing FROM-clause entry for table "temp_table" Where: PL/pgSQL function validation() line 21 at IF

Here is how my staging.validation table looks -

https://docs.google.com/spreadsheets/d/1bXO9gqFS-GtcC1qJtgNbFkR6ygOuPtR_RZoU7VNhgrI/edit?usp=sharing

First, you don't have to use DECLARE for every variable, it's enough with one.

DECLARE
    counter INTEGER;
    minsid INTEGER;
    maxsid INTEGER;
    rec RECORD;
    stmt varchar;

Second, you can't use the temp_table.col3 just like that, you have to query it because it's a table. You could create a variable and query into the table or you could directly make the query.

Variable:

-- First you declare de varialbe:
DECLARE
    temp BOOLEAN;

... -- rest of your code

temp := temp_table.col3 FROM temp_table WHERE temp_table.col2=counter;
-- you need something to make the query, here as a test I put col2=counter
IF temp=false THEN
... -- rest of your code

Directly:

... -- rest of your code
IF (SELECT temp_table.col3 FROM temp_table WHERE temp_table.col2=counter)=false THEN
-- Again, you need something to make the query
... -- rest of your code

And third, your function has RETURNS text , in your pl the return is missing;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM